run.py 19 KB

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