run.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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.common.exceptions import NoSuchElementException
  8. from selenium.webdriver.common.by import By
  9. from bs4 import BeautifulSoup
  10. from utility import database_access as DA
  11. from utility.parseutils import *
  12. from utility.connect import *
  13. from datetime import datetime
  14. import traceback
  15. import dataset
  16. import pandas as pd
  17. import time
  18. import json
  19. import re
  20. # import pyautogui as pag
  21. def serive_create(profilepath):
  22. option = webdriver.ChromeOptions()
  23. option.add_argument('--disable-web-security')
  24. option.add_argument('--allow-running-insecure-content')
  25. option.add_argument("--user-data-dir=C:\\Users\\noodles\\AppData\\Local\\Google\\Chrome\\User Data")
  26. option.add_argument("profile-directory="+profilepath)
  27. driver = webdriver.Chrome('./utility/chromedriver_20211103/chromedriver', options=option)
  28. executor_url = driver.command_executor._url
  29. session_id = driver.session_id
  30. print (session_id)
  31. print (executor_url)
  32. time.sleep(3)
  33. return driver
  34. def brower_start():
  35. options = webdriver.ChromeOptions()
  36. browser = webdriver.Remote(
  37. command_executor='http://192.53.174.202:4444/wd/hub',
  38. desired_capabilities=options.to_capabilities()
  39. )
  40. return browser
  41. def keyin_keyword(driver, keyword):
  42. button = driver.find_element_by_id("searchbox")
  43. driver.implicitly_wait(30)
  44. ActionChains(driver).move_to_element(button).send_keys(keyword).send_keys(Keys.RETURN).perform()
  45. time.sleep(3)
  46. # element = driver.find_element_by_class_name("V0h1Ob-haAclf")
  47. # driver.implicitly_wait(30)
  48. # ActionChains(driver).move_to_element(element).click(element).perform()
  49. def open_time(driver):
  50. element = driver.find_element_by_xpath('//*[@id="pane"]/div/div[1]/div/div/div[9]/div[2]')
  51. if element.text.find('預訂') == -1:
  52. element = driver.find_element_by_xpath('//*[@id="pane"]/div/div[1]/div/div/div[9]/div[2]')
  53. driver.implicitly_wait(20)
  54. ActionChains(driver).move_to_element(element).click(element).perform()
  55. return 1
  56. else:
  57. return 0
  58. def get_shop_info(driver, output, shop_soup):
  59. current_url_split = driver.current_url.split('@')[1].split(',')
  60. output['lon'] = current_url_split[1]
  61. output['lat'] = current_url_split[0]
  62. location = shop_soup.find('button',{'data-item-id':'oloc'})['aria-label'].split(' ')
  63. output['city'] = location[-1]
  64. output['area'] = location[-2]
  65. try:
  66. output['addr'] = shop_soup.find('button',{'data-item-id':'address'})['aria-label'].replace('地址:', '')
  67. except:
  68. output['addr'] = ''
  69. try:
  70. output['tel'] = blank_check(shop_soup.find('button',{'data-tooltip':'複製電話號碼'})['aria-label'].split(':')[1])
  71. except:
  72. output['tel'] = ''
  73. print(output['addr'], ', ' ,output['tel'])
  74. for key in element_list:
  75. try:
  76. element = element_list[key]
  77. if len(element) == 3:
  78. value = shop_soup.find(element[0],element[1])[element[2]]
  79. else:
  80. tmp_value = shop_soup.find(element[0],element[1])
  81. if tmp_value:
  82. value = tmp_value.text
  83. else:
  84. value = ''
  85. output[key] = value_check(key, value)
  86. except:
  87. output[key] = ''
  88. return output
  89. def get_intro_info(driver, output):
  90. element = driver.find_element_by_xpath('//*[@id="pane"]/div/div[1]/div/div/div[6]')
  91. driver.implicitly_wait(20)
  92. ActionChains(driver).move_to_element(element).click(element).perform()
  93. page_down_(driver, "//div[@class='siAUzd-neVct section-scrollbox cYB2Ge-oHo7ed cYB2Ge-ti6hGc']", 3)
  94. intro_soup = BeautifulSoup(driver.page_source, 'html.parser')
  95. for key in intro_list:
  96. elements = intro_soup.find('div',{'aria-label':key})
  97. if elements:
  98. element = elements.find_all('li',{'class':'LQjNnc-p83tee-JNdkSc-ibnC6b'})
  99. count = 0
  100. tmp = []
  101. for ele in element:
  102. # if ele.find('img',{'src':"//www.gstatic.com/images/icons/material/system_gm/2x/check_black_18dp.png"}):
  103. if ele.find('img',{'src':"//www.gstatic.com/images/icons/material/system_gm/1x/check_black_18dp.png"}):
  104. tmp += [{
  105. 'id':count,
  106. intro_list[key][1]: blank_check(ele.text)
  107. }]
  108. count += 1
  109. print(str(tmp))
  110. output[intro_list[key][0]] = str(tmp)
  111. else:
  112. output[intro_list[key][0]] = '[]'
  113. driver.back()
  114. return output
  115. def get_time_list(shop_soup, output):
  116. periods = []
  117. weekday_text = []
  118. open_now = blank_check(shop_soup.find('span', {'class':'LJKBpe-Tswv1b-hour-text'}).text.split('\xa0')[0])
  119. if open_now == '永久停業' or open_now == '暫時關閉':
  120. output['open_now'] = 'False'
  121. else:
  122. output['open_now'] = 'True'
  123. for tr_ in shop_soup.find_all('tr'):
  124. if tr_.find('div').text.replace(' ','') != '':
  125. week = tr_.find('div').text
  126. time_list = [blank_check(i.text) for i in tr_.find_all('li')]
  127. for time_ in time_list:
  128. if time_ == '24 小時營業':
  129. periods += [{
  130. "open":{
  131. "day": week_list[week],
  132. "time": 0000
  133. },
  134. "close":{
  135. "day": week_list[week],
  136. "time": ''
  137. }
  138. }]
  139. elif time_ == '休息':
  140. periods += [{
  141. "open":{
  142. "day": week_list[week],
  143. "time": ''
  144. },
  145. "close":{
  146. "day": week_list[week],
  147. "time": ''
  148. }
  149. }]
  150. else:
  151. start, end = time_.split('–')
  152. end_hour, end_min = end.split(':')
  153. start_hour, start_min = start.split(':')
  154. if end_hour < start_hour:
  155. end_day = week_list[week] + 1
  156. else:
  157. end_day = week_list[week]
  158. periods += [{
  159. "open":{
  160. "day": week_list[week],
  161. "time": start.replace(':','')
  162. },
  163. "close":{
  164. "day": end_day,
  165. "time": end.replace(':','')
  166. }
  167. }]
  168. weekday_text += ["{}: {}".format(week, ', '.join(time_list))]
  169. output['periods'] = str(periods)
  170. output['weekday_text'] = str(weekday_text)
  171. return output
  172. def get_reviews(driver, output):
  173. wait = WebDriverWait(driver, 30)
  174. more_reviews_css = "button[jsaction='pane.rating.moreReviews']"
  175. wait.until(
  176. EC.element_to_be_clickable((By.CSS_SELECTOR, more_reviews_css))
  177. )
  178. element = driver.find_element_by_css_selector(more_reviews_css)
  179. driver.implicitly_wait(20)
  180. ActionChains(driver).move_to_element(element).click(element).perform()
  181. time.sleep(0.5)
  182. page_down_(driver, "//div[@class='siAUzd-neVct siAUzd-neVct-H9tDt']", 10)
  183. all_photo = driver.find_elements_by_class_name('ODSEW-ShBeI-xJzy8c-bF1uUb')
  184. for ap in all_photo:
  185. ap.click()
  186. all_review = driver.find_elements_by_css_selector('button[aria-label="顯示更多"')
  187. for ap in all_review:
  188. ap.click()
  189. comment_soup = BeautifulSoup(driver.page_source, 'html.parser')
  190. count = 0
  191. reviews = []
  192. for comment in comment_soup.find_all('div',{'class':'ODSEW-ShBeI'}):
  193. comment_a_tag = comment.find_all('a')
  194. author_name = blank_check(comment_a_tag[1].find('div', class_= 'ODSEW-ShBeI-title').text)
  195. profile_photo_url = comment_a_tag[0].find('img')['src']
  196. rating = blank_check(comment.find('span',{'role':'img'})['aria-label'].replace('顆星', ''))
  197. text = comment.find('div', class_='ODSEW-ShBeI-ShBeI-content').text
  198. created_at = comment.find('span', class_='ODSEW-ShBeI-RgZmSc-date').text
  199. photos = []
  200. c = 0
  201. for i in comment.find_all('button', class_='ODSEW-ShBeI-xJzy8c'):
  202. path = i['style'].split(';')[0].split('url')[1].replace('\"','').replace('(','').replace(')','')
  203. photos += [path]
  204. c += 1
  205. reviews += [{
  206. 'id': comment.find('a')['href'].split('/')[5],
  207. 'author_name': author_name,
  208. 'profile_photo_url': profile_photo_url,
  209. 'rating': int(rating),
  210. 'text': text,
  211. 'created_at': created_at,
  212. 'photos': photos
  213. }]
  214. count += 1
  215. output['reviews'] = str(reviews)
  216. driver.back()
  217. return output
  218. # def get_photo(output, shop_soup):
  219. # shop_photo = {}
  220. # for i in shop_soup.find('div',{'aria-label':'{}的相片'.format(output['name'])}).find_all('button'):
  221. # try:
  222. # if i['aria-label'] == '街景服務和 360 度相片' or i['aria-label'] == '影片':
  223. # continue
  224. # shop_photo[i['aria-label']] = i.find('img')['src']
  225. # except:
  226. # pass
  227. # output['shop_photo'] = shop_photo
  228. # return output
  229. def find_photo_list(driver):
  230. time.sleep(0.5)
  231. wait = WebDriverWait(driver, 60)
  232. wait.until(
  233. EC.element_to_be_clickable((By.XPATH, '//*[@id="pane"]/div/div[1]/div/div/div[3]/div[1]/div[1]/div/a'))
  234. )
  235. page_down_(driver,'//*[@id="pane"]/div/div[1]/div/div/div[3]/div[1]/div[1]/div/a' , 10)
  236. photo_soup = BeautifulSoup(driver.page_source, 'html.parser')
  237. photo_url = []
  238. count = 0
  239. for i in photo_soup.find_all('a', class_='mWq4Rd-eEDwDf'):
  240. if count > 5: break
  241. a_url = i.find('div', class_='mWq4Rd-HiaYvf-CNusmb-gevUs loaded')
  242. if a_url:
  243. if a_url.find('width') != -1:
  244. sentence = a_url['style']
  245. photo = re.search(r'https:(.*)\"', sentence)
  246. photo_url += [photo.group(0).replace('\"','')]
  247. count += 1
  248. return photo_url
  249. def find_big_photo(output, driver):
  250. element = driver.find_element(By.CSS_SELECTOR, "div[aria-label='{}的相片']".format(output['name']))
  251. ActionChains(driver).move_to_element(element).click(element).perform()
  252. output['shop_photo'] = '[]'
  253. output['menu_photo'] = '[]'
  254. photo_map = {
  255. '全部': 'shop_photo',
  256. '菜單': 'menu_photo'
  257. }
  258. tab_dict = {}
  259. for tab_index in [0, 1, 2]:
  260. photo_name = driver.find_element(By.CSS_SELECTOR, "button[data-tab-index='{}']".format(tab_index)).text
  261. if photo_name == '菜單':
  262. tab_dict[photo_name] = tab_index
  263. elif photo_name == '全部':
  264. tab_dict[photo_name] = tab_index
  265. print(tab_dict)
  266. for tab_ in tab_dict:
  267. tab_index = tab_dict[tab_]
  268. print(tab_index)
  269. wait = WebDriverWait(driver, 60)
  270. wait.until(
  271. EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-tab-index='{}']".format(tab_index)))
  272. )
  273. element = driver.find_element(By.CSS_SELECTOR, "button[data-tab-index='{}']".format(tab_index))
  274. ActionChains(driver).move_to_element(element).click(element).perform()
  275. photo_list = find_photo_list(driver)
  276. output[photo_map[tab_]] = str(photo_list)
  277. return output
  278. def get_url_list(driver):
  279. # wait = WebDriverWait(driver, 10)
  280. # wait.until(
  281. # EC.element_to_be_clickable((By.XPATH, '//*[@id="sGi9mc-m5SR9c-bottom-pane"]/div/div[1]/div/div/div/div[1]/div[2]/div[2]'))
  282. # )
  283. # driver.back()
  284. time.sleep(2)
  285. for i in range(5, 43, 2):
  286. 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)
  287. url_soup = BeautifulSoup(driver.page_source, 'html.parser')
  288. url_list = []
  289. for i in url_soup.find_all('a'):
  290. try:
  291. if i['href'].find('maps/place') != -1:
  292. url_list += [[i['href'], i['aria-label']]]
  293. except:
  294. pass
  295. return url_list
  296. def data_select_insert(db, table_name, table_col, data):
  297. tmp = []
  298. for name_ in table_col:
  299. if name_ == 'crawler_date':
  300. continue
  301. if name_ == 'lon' or name_ == 'lat':
  302. tmp += [float(data[name_])]
  303. else:
  304. tmp += [data[name_]]
  305. tmp += [datetime.today().strftime("%Y/%m/%d %H:%M")]
  306. insert_sql = """INSERT IGNORE INTO {}{} VALUES {}"""\
  307. .format(table_name, str(tuple(table_col)).replace('\'',''), tuple(tmp))
  308. DA.mysql_insert_data(db, insert_sql)
  309. def time_click(driver):
  310. status = ''
  311. try:
  312. time_css = "span[aria-label='顯示本週營業時間']"
  313. element = driver.find_element_by_css_selector(time_css)
  314. driver.implicitly_wait(30)
  315. ActionChains(driver).move_to_element(element).click(element).perform()
  316. status = '正常'
  317. except NoSuchElementException:
  318. time_css = "div[aria-expanded='false']"
  319. elem = driver.find_element_by_css_selector(time_css)
  320. if elem:
  321. status = '暫時關閉'
  322. return status
  323. def get_not_cralwer_url(keyword):
  324. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/google_poi?charset=utf8mb4')
  325. table = db['shop_item_list']
  326. url_list = list(table.find(keyword=keyword))
  327. shop_item = [i['item_url'] for i in db.query('SELECT item_url FROM shop_list where keyword="{}"'.format(keyword))]
  328. error_item = [i['item_url'] for i in db.query('SELECT item_url FROM error_list where keyword="{}"'.format(keyword))]
  329. url_pd = pd.DataFrame(url_list, columns=url_list[0].keys())
  330. url_pd['item_url_length'] = url_pd.item_url.apply(lambda x: len(x))
  331. url_pd = url_pd[url_pd['item_url_length']!=1000]
  332. url_pd = url_pd[~url_pd['item_url'].isin(shop_item)]
  333. url_pd = url_pd[~url_pd['item_url'].isin(error_item)]
  334. print('have {} URL list'.format(len(url_pd)))
  335. # url_list = pd.read_csv('result/shop_item_list_20211210.csv', index_col=0)
  336. return url_pd
  337. def serive_create_linux(profilepath):
  338. option = webdriver.ChromeOptions()
  339. option.add_argument('--headless')
  340. option.add_argument('--no-sandbox')
  341. option.add_argument('--disable-web-security')
  342. option.add_argument('--allow-running-insecure-content')
  343. option.add_argument('--incognito')
  344. option.add_argument(
  345. 'user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0')
  346. # option.add_argument("--user-data-dir=C:\\Users\\noodles\\AppData\\Local\\Google\\Chrome\\User Data")
  347. option.add_argument(
  348. "--user-data-dir=/home/noodlesloves/.config/google-chrome/")
  349. option.add_argument("profile-directory="+profilepath)
  350. driver = webdriver.Chrome('utility/chromedriver', options=option)
  351. # driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', chrome_options=option,
  352. # service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])
  353. executor_url = driver.command_executor._url
  354. session_id = driver.session_id
  355. print(session_id)
  356. print(executor_url)
  357. return driver
  358. def page_down_(driver, xpath_css, time_):
  359. elmts = driver.find_elements_by_xpath(xpath_css)
  360. print(elmts)
  361. if len(elmts)>1:
  362. elmt=elmts[1]
  363. else:
  364. elmt=elmts[0]
  365. actions = ActionChains(driver)
  366. actions.move_to_element(elmt).click().perform()
  367. for i in range(time_):
  368. try:
  369. actions = ActionChains(driver)
  370. actions.send_keys(Keys.PAGE_DOWN).perform()
  371. except:
  372. traceback.print_exc()
  373. time.sleep(0.5)
  374. def main():
  375. keyword = '咖啡'
  376. db = DA.mysql_connect(MYSQL_CONFIG, DB_NAME)
  377. url_pd = get_not_cralwer_url(keyword)
  378. print('drvier start...')
  379. driver = brower_start()
  380. # driver = serive_create('Profile 1')
  381. # profilepath = 'Profile 1'
  382. # driver = serive_create_linux(profilepath)
  383. for key, row in url_pd.iterrows():
  384. try:
  385. name = row['name']
  386. item_url = row['item_url']
  387. print(key, name, ': ' ,item_url)
  388. print('start...')
  389. driver.get(item_url)
  390. page_down_(driver, "//div[@class='x3AX1-LfntMc-header-title-ij8cu']", 6)
  391. time_status = time_click(driver)
  392. time.sleep(0.5)
  393. shop_soup = BeautifulSoup(driver.page_source, 'html.parser')
  394. output = {
  395. 'name': blank_check(shop_soup.find('h1', class_='x3AX1-LfntMc-header-title-title').text)
  396. }
  397. print(output['name'])
  398. output = get_shop_info(driver, output, shop_soup)
  399. output = get_intro_info(driver, output)
  400. output = get_time_list(shop_soup, output)
  401. if output['user_ratings_total'] == '':
  402. output['reviews'] = ''
  403. else:
  404. output = get_reviews(driver, output)
  405. output = find_big_photo(output, driver)
  406. output_name = output['name'].replace('(','').replace(')', '')
  407. query_name = '{}+{}'.format(output_name, output['addr'])
  408. query_name = query_name.replace(' ','')
  409. output['item_url'] = item_url
  410. output['keyword'] = keyword
  411. output['google_url'] = 'https://www.google.com.tw/search?q={}'.format(query_name)
  412. data_select_insert(db, SHOP_LIST_TABLE, SHOP_LIST_TABLE_COL, output)
  413. except:
  414. error_table_col = ['name', 'lon', 'lat', 'keyword', 'item_url', 'crawler_date']
  415. data_select_insert(db, 'error_list', error_table_col, row)
  416. driver.close()
  417. driver = brower_start()
  418. # driver = serive_create_linux(profilepath)
  419. if __name__ == '__main__':
  420. main()