shop_item_list.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # -*- coding: utf-8 -*-
  2. from selenium import webdriver
  3. from selenium.webdriver.common.action_chains import ActionChains
  4. from selenium.webdriver.common.keys import Keys
  5. from selenium.webdriver.support import expected_conditions as EC
  6. from selenium.webdriver.support.wait import WebDriverWait
  7. from selenium.webdriver.common.by import By
  8. import selenium
  9. import traceback
  10. from bs4 import BeautifulSoup
  11. from utility import database_access as DA
  12. from utility.parseutils import *
  13. from utility.connect import *
  14. from datetime import datetime
  15. import pandas as pd
  16. import dataset
  17. import time
  18. import json
  19. import re
  20. import sys, os
  21. def brower_start(port):
  22. options = webdriver.ChromeOptions()
  23. browser = webdriver.Remote(
  24. #command_executor='http://192.53.174.202:4444/wd/hub',
  25. command_executor='http://127.0.0.1:'+str(port)+'/wd/hub',
  26. desired_capabilities=options.to_capabilities()
  27. )
  28. return browser
  29. def page_down_(driver, xpath_css, time_):
  30. elmts = driver.find_elements_by_xpath(xpath_css)
  31. print(elmts)
  32. if len(elmts)>1:
  33. elmt=elmts[1]
  34. else:
  35. elmt=elmts[0]
  36. actions = ActionChains(driver)
  37. actions.move_to_element(elmt).click().perform()
  38. for i in range(time_):
  39. try:
  40. actions = ActionChains(driver)
  41. actions.send_keys(Keys.PAGE_DOWN).perform()
  42. except:
  43. traceback.print_exc()
  44. time.sleep(0.5)
  45. def get_url_list(driver):
  46. # for i in range(5, 43, 2):
  47. # try:
  48. # wait = WebDriverWait(driver, 60)
  49. # wait.until(
  50. # EC.element_to_be_clickable((By.XPATH, '//*[@id="pane"]/div/div[1]/div/div/div[2]/div[1]/div[{}]/div/a'.format(i)))
  51. # )
  52. # driver.find_element(By.XPATH,'//*[@id="pane"]/div/div[1]/div/div/div[2]/div[1]/div[{}]/div/a'.format(i)).send_keys(Keys.DOWN)
  53. # time.sleep(0.5)
  54. # except:
  55. # pass
  56. # wait = WebDriverWait(driver, 30)
  57. # try:
  58. # wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ppdPk-Ej1Yeb-LgbsSe-tJiF1e"]')))
  59. # except selenium.common.exceptions.TimeoutException:
  60. # traceback.print_exc()
  61. # return "EMPTY"
  62. page_down_(driver, '//div[@class="TFQHme"]', 8)
  63. url_soup = BeautifulSoup(driver.page_source, 'html.parser')
  64. url_list = []
  65. for i in url_soup.find_all('a'):
  66. try:
  67. if i['href'].find('maps/place') != -1:
  68. url_list += [[i['href'], i['aria-label']]]
  69. except:
  70. pass
  71. # print(len(url_list))
  72. return url_list
  73. def keyin_keyword(driver, keyword):
  74. button = driver.find_element_by_id("searchbox")
  75. driver.implicitly_wait(30)
  76. ActionChains(driver).move_to_element(button).send_keys(keyword).send_keys(Keys.RETURN).perform()
  77. time.sleep(3)
  78. # def get_crawler_list(db):
  79. # result = db.query('select keyword, count(*) from shop_item_list group by keyword')
  80. # result = pd.DataFrame([i for i in result])
  81. # result.columns = ['keyword', 'count']
  82. # result = result[result['count'] < 100]
  83. # keyword = result.sample(1).iloc[0]['keyword']
  84. # num=0
  85. # cursor=db.query('select num from progress_list2 where kw = "'+keyword+'"')
  86. # for c in cursor:
  87. # num=c['num']
  88. # break
  89. # cursor=db.query('select * from lat_lon_loc where num >= '+str(num))
  90. # # cursor=db.query('select * from lat_lon_loc')
  91. # lst=[]
  92. # for c in cursor:
  93. # lst.append({'num':c['num'],'loc':c['loc'],'lat':c['lat'],'lon':c['lon']})
  94. # return keyword, lst
  95. def get_crawler_list(db):
  96. result = db.query('select distinct(keyword) from shop_item_list order by keyword')
  97. result = pd.DataFrame([i for i in result])
  98. progress = db.query('select distinct(kw) from progress_list2')
  99. progress = pd.DataFrame([i for i in progress])
  100. if len(progress) != 0:
  101. keyword = result[~result['keyword'].isin(progress.kw.to_list())].iloc[0].values[0]
  102. else:
  103. keyword = result.iloc[0].values[0]
  104. return keyword
  105. def main():
  106. # data = pd.read_csv('lat_long_location.csv', index_col = 0)
  107. # keyword = '麻辣火鍋'
  108. lon_lat = [[121.567,25.038], [121.567,25.046], [121.543,25.046], [121.543,25.038]]
  109. port=4447
  110. if len(sys.argv) > 1 :
  111. port=int(sys.argv[1])
  112. print('restart docker p{}'.format(port))
  113. os.system('sudo docker container restart pp'+str(port))
  114. time.sleep(8)
  115. # if len(sys.argv) >2:
  116. # port=int(sys.argv[2])
  117. print('drvier start...')
  118. driver = brower_start(port)
  119. # db = DA.mysql_connect(MYSQL_CONFIG, DB_NAME)
  120. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/google_poi?charset=utf8mb4')
  121. table=db['shop_item_list3']
  122. table2=db['progress_list2']
  123. for i in range(20):
  124. try:
  125. keyword = get_crawler_list(db)
  126. print(keyword)
  127. c = 0
  128. for row in lon_lat:
  129. c += 1
  130. # latitude = row['lat'] #緯度
  131. # longitude = row['lon'] #精度
  132. latitude = row[1] #緯度
  133. longitude = row[0] #精度
  134. # table2.upsert({'kw':keyword,'num':row['num']},['kw'])
  135. table2.insert({'kw':keyword,'num':c})
  136. url = 'https://www.google.com.tw/maps/@{},{},15z?hl=zh-TW'.format(latitude, longitude)
  137. driver.get(url)
  138. keyin_keyword(driver, keyword)
  139. failcnt = 0
  140. for page in range(5):
  141. print(keyword, latitude, longitude, page)
  142. url_list = get_url_list(driver)
  143. duplicate = 0
  144. # shop_item_list_col = ['name','lon','lat','keyword','item_url','crawler_date']
  145. for item in url_list:
  146. try:
  147. table.insert({'name':item[1],'lon':longitude, 'lat':latitude, \
  148. 'keyword':keyword, 'item_url':item[0],'crawler_date':datetime.today().strftime("%Y/%m/%d %H:%M")})
  149. except:
  150. duplicate += 1
  151. print(len(url_list), duplicate)
  152. # result = [item[1], longitude, latitude, keyword, item[0], datetime.today().strftime("%Y/%m/%d %H:%M")]
  153. # insert_sql = """INSERT IGNORE INTO {}{} VALUES {}"""\
  154. # .format('shop_item_list', str(tuple(shop_item_list_col)).replace('\'',''), tuple(result))
  155. # DA.mysql_insert_data(db, insert_sql)
  156. if page < 2 :
  157. element = driver.find_element_by_id('ppdPk-Ej1Yeb-LgbsSe-tJiF1e')
  158. driver.implicitly_wait(30)
  159. ActionChains(driver).move_to_element(element).click(element).perform()
  160. except:
  161. pass
  162. if __name__ == '__main__':
  163. main()