shop_item_list.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. e = driver.find_element_by_css_selector('span[class="Jl2AFb"]')
  31. result_count = e.text.split('-')[1].replace(' 項結果','')
  32. print(result_count)
  33. if int(result_count) > 5:
  34. for i in range(time_):
  35. e = driver.find_elements_by_css_selector('div[class="TFQHme"]')
  36. action = webdriver.common.action_chains.ActionChains(driver)
  37. action.move_to_element_with_offset(e[-1], e[-1].size['width'] + 1 , 0)
  38. action.click()
  39. action.perform()
  40. time.sleep(0.5)
  41. # elmts = driver.find_elements_by_xpath(xpath_css)
  42. # print(elmts)
  43. # if len(elmts)>1:
  44. # elmt=elmts[1]
  45. # else:
  46. # elmt=elmts[0]
  47. # actions = ActionChains(driver)
  48. # actions.move_to_element(elmt).click().perform()
  49. # for i in range(time_):
  50. # try:
  51. # actions = ActionChains(driver)
  52. # actions.send_keys(Keys.PAGE_DOWN).perform()
  53. # except:
  54. # traceback.print_exc()
  55. # time.sleep(0.5)
  56. def get_url_list(driver):
  57. # for i in range(5, 43, 2):
  58. # try:
  59. # wait = WebDriverWait(driver, 60)
  60. # wait.until(
  61. # EC.element_to_be_clickable((By.XPATH, '//*[@id="pane"]/div/div[1]/div/div/div[2]/div[1]/div[{}]/div/a'.format(i)))
  62. # )
  63. # 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)
  64. # time.sleep(0.5)
  65. # except:
  66. # pass
  67. # wait = WebDriverWait(driver, 30)
  68. # try:
  69. # wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ppdPk-Ej1Yeb-LgbsSe-tJiF1e"]')))
  70. # except selenium.common.exceptions.TimeoutException:
  71. # traceback.print_exc()
  72. # return "EMPTY"
  73. page_down_(driver, '//div[@class="TFQHme"]', 8)
  74. url_soup = BeautifulSoup(driver.page_source, 'html.parser')
  75. url_list = []
  76. for i in url_soup.find_all('a'):
  77. try:
  78. if i['href'].find('maps/place') != -1:
  79. url_list += [[i['href'], i['aria-label']]]
  80. except:
  81. pass
  82. # print(len(url_list))
  83. return url_list
  84. def keyin_keyword(driver, keyword):
  85. button = driver.find_element_by_id("searchbox")
  86. driver.implicitly_wait(30)
  87. ActionChains(driver).move_to_element(button).send_keys(keyword).send_keys(Keys.RETURN).perform()
  88. time.sleep(3)
  89. # def get_crawler_list(db):
  90. # result = db.query('select keyword, count(*) from shop_item_list group by keyword')
  91. # result = pd.DataFrame([i for i in result])
  92. # result.columns = ['keyword', 'count']
  93. # result = result[result['count'] < 100]
  94. # keyword = result.sample(1).iloc[0]['keyword']
  95. # num=0
  96. # cursor=db.query('select num from progress_list2 where kw = "'+keyword+'"')
  97. # for c in cursor:
  98. # num=c['num']
  99. # break
  100. # cursor=db.query('select * from lat_lon_loc where num >= '+str(num))
  101. # # cursor=db.query('select * from lat_lon_loc')
  102. # lst=[]
  103. # for c in cursor:
  104. # lst.append({'num':c['num'],'loc':c['loc'],'lat':c['lat'],'lon':c['lon']})
  105. # return keyword, lst
  106. def get_crawler_list(db):
  107. result = db.query('select * from shop_item_list order by keyword')
  108. result = pd.DataFrame([i for i in result])
  109. result = result[~result.keyword.str.contains('項')]
  110. progress = db.query('select distinct(kw) from progress_list2 where num < 367')
  111. progress = pd.DataFrame([i for i in progress])
  112. if len(progress) != 0:
  113. keyword = result[~result['keyword'].isin(progress.kw.to_list())].iloc[0]['keyword']
  114. else:
  115. keyword = result.iloc[0]['keyword']
  116. return keyword
  117. def get_lon_lat_list(db, keyword):
  118. num=0
  119. cursor=db.query('select num from progress_list where kw = "'+keyword+'"')
  120. for c in cursor:
  121. num=c['num']
  122. break
  123. cursor=db.query('select * from lat_lon_loc where num >= '+str(num))
  124. lst=[]
  125. for c in cursor:
  126. lst.append({'num':c['num'],'loc':c['loc'],'lat':c['lat'],'lon':c['lon']})
  127. return lst
  128. def main():
  129. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/google_poi?charset=utf8mb4')
  130. table = db['shop_item_list3']
  131. table2 = db['progress_list2']
  132. port=4447
  133. if len(sys.argv) > 1 :
  134. port=int(sys.argv[1])
  135. print('restart docker p{}'.format(port))
  136. os.system('sudo docker container restart p'+str(port))
  137. time.sleep(8)
  138. print('drvier start...')
  139. driver = brower_start(port)
  140. for i in range(10):
  141. try:
  142. keyword = get_crawler_list(db)
  143. print(keyword)
  144. lst = get_lon_lat_list(db, keyword)
  145. print(keyword, len(lst))
  146. for r in lst:
  147. latitude = r['lat'] #緯度
  148. longitude = r['lon'] #精度
  149. table2.upsert({'kw':keyword,'num':r['num']},['kw'])
  150. url = 'https://www.google.com.tw/maps/@{},{},15z?hl=zh-TW'.format(latitude, longitude)
  151. driver.get(url)
  152. keyin_keyword(driver, keyword)
  153. failcnt = 0
  154. for page in range(10):
  155. print(keyword, latitude, longitude, page)
  156. url_list = get_url_list(driver)
  157. duplicate = 0
  158. # shop_item_list_col = ['name','lon','lat','keyword','item_url','crawler_date']
  159. for item in url_list:
  160. try:
  161. table.insert({'name':item[1],'lon':longitude, 'lat':latitude, \
  162. 'keyword':keyword, 'item_url':item[0],'crawler_date':datetime.today().strftime("%Y/%m/%d %H:%M")})
  163. except:
  164. duplicate += 1
  165. print(len(url_list), duplicate)
  166. # result = [item[1], longitude, latitude, keyword, item[0], datetime.today().strftime("%Y/%m/%d %H:%M")]
  167. # insert_sql = """INSERT IGNORE INTO {}{} VALUES {}"""\
  168. # .format('shop_item_list', str(tuple(shop_item_list_col)).replace('\'',''), tuple(result))
  169. # DA.mysql_insert_data(db, insert_sql)
  170. if page < 2 :
  171. element = driver.find_element_by_id('ppdPk-Ej1Yeb-LgbsSe-tJiF1e')
  172. if element.get_attribute('disabled'):
  173. break
  174. driver.implicitly_wait(30)
  175. ActionChains(driver).move_to_element(element).click(element).perform()
  176. except:
  177. pass
  178. if __name__ == '__main__':
  179. main()