run.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. from bs4 import BeautifulSoup
  9. from utility import database_access as DA
  10. from utility.parseutils import *
  11. from utility.connect import *
  12. import pandas as pd
  13. import time
  14. import json
  15. import re
  16. # import pyautogui as pag
  17. def serive_create(profilepath):
  18. option = webdriver.ChromeOptions()
  19. option.add_argument('--disable-web-security')
  20. option.add_argument('--allow-running-insecure-content')
  21. option.add_argument("--user-data-dir=C:\\Users\\noodles\\AppData\\Local\\Google\\Chrome\\User Data")
  22. option.add_argument("profile-directory="+profilepath)
  23. driver = webdriver.Chrome('./utility/chromedriver_20211103/chromedriver', options=option)
  24. executor_url = driver.command_executor._url
  25. session_id = driver.session_id
  26. print (session_id)
  27. print (executor_url)
  28. time.sleep(3)
  29. return driver
  30. def brower_start():
  31. options = webdriver.ChromeOptions()
  32. browser = webdriver.Remote(
  33. command_executor='http://192.53.174.202:4444/wd/hub',
  34. desired_capabilities=options.to_capabilities()
  35. )
  36. return browser
  37. def keyin_keyword(driver, keyword):
  38. button = driver.find_element_by_id("searchbox")
  39. driver.implicitly_wait(30)
  40. ActionChains(driver).move_to_element(button).send_keys(keyword).send_keys(Keys.RETURN).perform()
  41. time.sleep(3)
  42. element = driver.find_element_by_class_name("V0h1Ob-haAclf")
  43. driver.implicitly_wait(30)
  44. ActionChains(driver).move_to_element(element).click(element).perform()
  45. def open_time(driver):
  46. element = driver.find_element_by_xpath('//*[@id="pane"]/div/div[1]/div/div/div[9]/div[2]')
  47. if element.text.find('預訂') == -1:
  48. element = driver.find_element_by_xpath('//*[@id="pane"]/div/div[1]/div/div/div[9]/div[2]')
  49. driver.implicitly_wait(20)
  50. ActionChains(driver).move_to_element(element).click(element).perform()
  51. return 1
  52. else:
  53. return 0
  54. def get_shop_info(driver, output, shop_soup):
  55. current_url_split = driver.current_url.split('@')[1].split(',')
  56. output['lon'] = current_url_split[1]
  57. output['lat'] = current_url_split[0]
  58. location = shop_soup.find('button',{'data-item-id':'oloc'})['aria-label'].split(' ')
  59. output['city'] = location[-1]
  60. output['area'] = location[-2]
  61. print(location)
  62. output['addr'] = shop_soup.find('button',{'data-item-id':'address'})['aria-label'].replace('地址:', '')
  63. output['tel'] = blank_check(shop_soup.find('button',{'data-tooltip':'複製電話號碼'})['aria-label'].split(':')[1])
  64. print(output['addr'], output['tel'])
  65. for key in element_list:
  66. element = element_list[key]
  67. if len(element) == 3:
  68. value = shop_soup.find(element[0],element[1])[element[2]]
  69. else:
  70. tmp_value = shop_soup.find(element[0],element[1])
  71. if tmp_value:
  72. value = tmp_value.text
  73. else:
  74. value = ''
  75. output[key] = value_check(key, value)
  76. return output
  77. def get_intro_info(driver, output):
  78. element = driver.find_element_by_xpath('//*[@id="pane"]/div/div[1]/div/div/div[6]')
  79. driver.implicitly_wait(20)
  80. ActionChains(driver).move_to_element(element).click(element).perform()
  81. wait = WebDriverWait(driver, 30)
  82. item_xpath = "div[aria-label='{}簡介']".format(output['name'])
  83. wait.until(
  84. EC.element_to_be_clickable((By.CSS_SELECTOR, item_xpath))
  85. )
  86. time.sleep(1)
  87. intro_soup = BeautifulSoup(driver.page_source, 'html.parser')
  88. for key in intro_list:
  89. elements = intro_soup.find('div',{'aria-label':key})
  90. # print(elements)
  91. if elements:
  92. element = elements.find_all('li',{'class':'LQjNnc-p83tee-JNdkSc-ibnC6b'})
  93. # print(element)
  94. count = 0
  95. tmp = []
  96. for ele in element:
  97. if ele.find('img',{'src':"//www.gstatic.com/images/icons/material/system_gm/2x/check_black_18dp.png"}):
  98. tmp += [{
  99. 'id':count,
  100. intro_list[key][1]: blank_check(ele.text)
  101. }]
  102. count += 1
  103. output[intro_list[key][0]] = str(tmp)
  104. else:
  105. output[intro_list[key][0]] = []
  106. driver.back()
  107. return output
  108. def get_time_list(shop_soup, output):
  109. open_now = blank_check(shop_soup.find('span', {'class':'LJKBpe-Tswv1b-hour-text'}).text.split('\xa0')[0])
  110. if open_now == '永久停業' or open_now == '暫時關閉':
  111. output['open_now'] = 'False'
  112. else:
  113. output['open_now'] = 'True'
  114. periods = []
  115. weekday_text = []
  116. for tr_ in shop_soup.find_all('tr'):
  117. if tr_.find('div').text.replace(' ','') != '':
  118. week = tr_.find('div').text
  119. time_list = [blank_check(i.text) for i in tr_.find_all('li')]
  120. for time_ in time_list:
  121. if time_ == '24 小時營業':
  122. periods += [{
  123. "open":{
  124. "day": week_list[week],
  125. "time": 0000
  126. },
  127. "close":{
  128. "day": week_list[week],
  129. "time": ''
  130. }
  131. }]
  132. elif time_ == '休息':
  133. periods += [{
  134. "open":{
  135. "day": week_list[week],
  136. "time": ''
  137. },
  138. "close":{
  139. "day": week_list[week],
  140. "time": ''
  141. }
  142. }]
  143. else:
  144. start, end = time_.split('–')
  145. end_hour, end_min = end.split(':')
  146. start_hour, start_min = start.split(':')
  147. if end_hour < start_hour:
  148. end_day = week_list[week] + 1
  149. else:
  150. end_day = week_list[week]
  151. periods += [{
  152. "open":{
  153. "day": week_list[week],
  154. "time": start.replace(':','')
  155. },
  156. "close":{
  157. "day": end_day,
  158. "time": end.replace(':','')
  159. }
  160. }]
  161. weekday_text += ["{}: {}".format(week, ', '.join(time_list))]
  162. output['periods'] = str(periods)
  163. output['weekday_text'] = str(weekday_text)
  164. return output
  165. def get_reviews(driver, output):
  166. wait = WebDriverWait(driver, 30)
  167. more_reviews_css = "button[jsaction='pane.rating.moreReviews']"
  168. wait.until(
  169. EC.element_to_be_clickable((By.CSS_SELECTOR, more_reviews_css))
  170. )
  171. element = driver.find_element_by_css_selector(more_reviews_css)
  172. driver.implicitly_wait(20)
  173. ActionChains(driver).move_to_element(element).click(element).perform()
  174. time.sleep(2)
  175. all_photo = driver.find_elements_by_class_name('ODSEW-ShBeI-xJzy8c-bF1uUb')
  176. for ap in all_photo:
  177. ap.click()
  178. all_review = driver.find_elements_by_css_selector('button[aria-label="顯示更多"')
  179. for ap in all_review:
  180. ap.click()
  181. comment_soup = BeautifulSoup(driver.page_source, 'html.parser')
  182. count = 0
  183. reviews = []
  184. for comment in comment_soup.find_all('div',{'class':'ODSEW-ShBeI'}):
  185. comment_a_tag = comment.find_all('a')
  186. author_name = blank_check(comment_a_tag[1].find('div', class_= 'ODSEW-ShBeI-title').text)
  187. profile_photo_url = comment_a_tag[0].find('img')['src']
  188. rating = blank_check(comment.find('span',{'role':'img'})['aria-label'].replace('顆星', ''))
  189. text = comment.find('div', class_='ODSEW-ShBeI-ShBeI-content').text
  190. created_at = comment.find('span', class_='ODSEW-ShBeI-RgZmSc-date').text
  191. photos = []
  192. c = 0
  193. for i in comment.find_all('button', class_='ODSEW-ShBeI-xJzy8c'):
  194. path = i['style'].split(';')[0].split('url')[1].replace('\"','').replace('(','').replace(')','')
  195. photos += [path]
  196. c += 1
  197. reviews += [{
  198. 'id': comment.find('a')['href'].split('/')[5],
  199. 'author_name': author_name,
  200. 'profile_photo_url': profile_photo_url,
  201. 'rating': int(rating),
  202. 'text': text,
  203. 'created_at': created_at,
  204. 'photos': photos
  205. }]
  206. count += 1
  207. output['reviews'] = reviews
  208. driver.back()
  209. return output
  210. # def get_photo(output, shop_soup):
  211. # shop_photo = {}
  212. # for i in shop_soup.find('div',{'aria-label':'{}的相片'.format(output['name'])}).find_all('button'):
  213. # try:
  214. # if i['aria-label'] == '街景服務和 360 度相片' or i['aria-label'] == '影片':
  215. # continue
  216. # shop_photo[i['aria-label']] = i.find('img')['src']
  217. # except:
  218. # pass
  219. # output['shop_photo'] = shop_photo
  220. # return output
  221. def find_photo_list(driver):
  222. wait = WebDriverWait(driver, 30)
  223. wait.until(
  224. EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[data-photo-index="5"]'))
  225. )
  226. for photo_id in range(6):
  227. driver.find_element(By.CSS_SELECTOR,'a[data-photo-index="{}"]'.format(photo_id)).send_keys(Keys.DOWN)
  228. time.sleep(1)
  229. photo_soup = BeautifulSoup(driver.page_source, 'html.parser')
  230. photo_url = []
  231. for photo_id in range(5):
  232. for i in photo_soup.select('a[data-photo-index="{}"]'.format(photo_id))[0].find_all('div'):
  233. if i['style'].find('width') != -1:
  234. sentence = i['style']
  235. photo = re.search(r'https:(.*)\"', sentence)
  236. photo_url += [photo.group(0).replace('\"','')]
  237. break
  238. return photo_url
  239. def find_big_photo(output, driver):
  240. element = driver.find_element(By.CSS_SELECTOR, "div[aria-label='{}的相片']".format(output['name']))
  241. ActionChains(driver).move_to_element(element).click(element).perform()
  242. photo_map = {
  243. 0: 'shop_photo',
  244. 2: 'menu_photo'
  245. }
  246. for tab_index in [0, 2]:
  247. wait = WebDriverWait(driver, 30)
  248. wait.until(
  249. EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-tab-index='{}']".format(tab_index)))
  250. )
  251. element = driver.find_element(By.CSS_SELECTOR, "button[data-tab-index='{}']".format(tab_index))
  252. ActionChains(driver).move_to_element(element).click(element).perform()
  253. photo_list = find_photo_list(driver)
  254. output[photo_map[tab_index]] = photo_list
  255. for i in range(2):
  256. driver.back()
  257. time.sleep(1)
  258. return output
  259. def get_url_list(driver):
  260. wait = WebDriverWait(driver, 10)
  261. wait.until(
  262. EC.element_to_be_clickable((By.XPATH, '//*[@id="sGi9mc-m5SR9c-bottom-pane"]/div/div[1]/div/div/div/div[1]/div[2]/div[2]'))
  263. )
  264. driver.back()
  265. time.sleep(2)
  266. for i in range(5, 43, 2):
  267. 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)
  268. url_soup = BeautifulSoup(driver.page_source, 'html.parser')
  269. url_list = []
  270. for i in url_soup.find_all('a'):
  271. try:
  272. if i['href'].find('maps/place') != -1:
  273. url_list += [[i['href'], i['aria-label']]]
  274. except:
  275. pass
  276. return url_list
  277. def main():
  278. data = pd.read_csv('lat_long_location.csv', index_col = 0)
  279. tmp = data.iloc[0]
  280. latitude = tmp['latitude'] #緯度
  281. longitude = tmp['longitude'] #精度
  282. url = 'https://www.google.com.tw/maps/@{},{},15z?hl=zh-TW'.format(latitude,longitude)
  283. # driver = serive_create('Profile 1')
  284. db = DA.mysql_connect(MYSQL_CONFIG, DB_NAME)
  285. print('drvier start...')
  286. driver = brower_start()
  287. driver.get(url)
  288. keyin_keyword(driver, '咖啡')
  289. url_list = get_url_list(driver)
  290. result = []
  291. # try:
  292. for item_url, name in url_list:
  293. print(name, ': ' ,item_url)
  294. driver.get(item_url)
  295. wait = WebDriverWait(driver, 120)
  296. time_css = "span[aria-label='顯示本週營業時間']"
  297. wait.until(
  298. EC.element_to_be_clickable((By.CSS_SELECTOR, time_css))
  299. )
  300. element = driver.find_element_by_css_selector(time_css)
  301. driver.implicitly_wait(30)
  302. ActionChains(driver).move_to_element(element).click(element).perform()
  303. time.sleep(1)
  304. shop_soup = BeautifulSoup(driver.page_source, 'html.parser')
  305. output = {
  306. 'name': blank_check(shop_soup.find('h1', class_='x3AX1-LfntMc-header-title-title').text)
  307. }
  308. print(output['name'])
  309. output = get_shop_info(driver, output, shop_soup)
  310. output = get_intro_info(driver, output)
  311. output = get_time_list(shop_soup, output)
  312. output = get_reviews(driver, output)
  313. output = find_big_photo(output, driver)
  314. output_name = output['name'].replace('(','').replace(')', '')
  315. output['google_url'] = 'https://www.google.com.tw/search?q={}+{}'.format(output_name, output['addr'])
  316. time.sleep(2)
  317. result += [output]
  318. with open('result/20211207_{}.json'.format(name), 'w') as f:
  319. json.dump(output, f)
  320. DA.data_select_insert(db, SHOP_LIST_TABLE, SHOP_LIST_TABLE_COL, output)
  321. break
  322. # except:
  323. # shop_soup = BeautifulSoup(driver.page_source, 'html.parser')
  324. # print("error {}".format(id_))
  325. # print(blank_check(shop_soup.find('h1', class_='x3AX1-LfntMc-header-title-title').text))
  326. if __name__ == '__main__':
  327. main()