run.py 20 KB

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