我已經從 TripAdvisor 中洗掉了 3 個酒店資訊頁面的網址并存盤在一個 csv 檔案中。匯入 csv 檔案后,我必須使用這 3 個 url 來抓取每個酒店名稱,獲取每個酒店的價格范圍及其酒店等級。使用了 Selenium 的工具。
| 姓名 | 關聯 |
|---|---|
| 上議院 | https://en.tripadvisor.com.hk/Hotel_Review-g294217-d1513860-Reviews-The_Upper_House-Hong_Kong.html |
| 圖示酒店 | https://en.tripadvisor.com.hk/Hotel_Review-g294217-d2031570-Reviews-Hotel_ICON-Hong_Kong.html |
| 香港 W | https://en.tripadvisor.com.hk/Hotel_Review-g294217-d1068719-Reviews-W_Hong_Kong-Hong_Kong.html |
這是我的代碼。當使用單個酒店的 URL 時,我可以抓取酒店的名稱。但是,當涉及到很多酒店要刮的時候,就行不通了。“for”回圈中似乎存在問題。
!pip install selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import csv
from time import sleep
from time import time
from random import randint
browser = webdriver.Chrome(executable_path= 'C:\ProgramData\Anaconda3\Lib\site-packages\jupyterlab\chromedriver.exe')
result_list=[]
def start_request(q):
r = browser.get(q)
print("crlawling " q)
return r
def parse(text):
container1 = browser.find_elements_by_xpath('//*[@id="taplc_hotel_review_atf_hotel_info_web_component_0"]')
mydict = {}
for results in container1:
try:
mydict['name'] = results.find_element_by_xpath('//*[@id="HEADING"]')
except Exception as e:
print(e)
print('not____________________________found')
mydict['name'] = 'null'
result_list.append(mydict)
with open('Best3HotelsLink.csv') as f:
reader = csv.DictReader(f)
for row in reader:
req = row['Link']
text = start_request(req)
parse(text)
sleep(randint(1,3))
import pandas as pd
df = pd.DataFrame(result_list)
df.to_csv('Detailed Hotelinfo.csv')
df
我也曾試圖刮過酒店等級和酒店的價格范圍,但徒勞無功。 酒店級 價格范圍
我想就如何解決上述問題尋求您的建議。非常感謝。
uj5u.com熱心網友回復:
如果您有很多資訊要報廢,我建議您每次都重新加載資訊:
試試這個代碼:
def parse(text):
time.sleep(2) # i suggzest you to add some time to wait to load the page
container1 = browser.find_elements_by_xpath('//*[@id="taplc_hotel_review_atf_hotel_info_web_component_0"]')
nbrcontainer = len(container1)
mydict = {}
for i in range(0, nbrcontainer):
container1 = browser.find_elements_by_xpath('//*[@id="taplc_hotel_review_atf_hotel_info_web_component_0"]')
results = container1[i]
try:
mydict['name'] = results.find_element_by_xpath('//*[@id="HEADING"]')
except Exception as e:
print(e)
print('not____________________________found')
mydict['name'] = 'null'
result_list.append(mydict)
uj5u.com熱心網友回復:
我不擅長硒,所以這里是如何用beautifulsoup來捕捉價格范圍和酒店等級。兩者都在具有相同 id (...) 的不同 div 中,因此很難刮擦。我不認為 selenium 可以處理第一個選擇器,但第二個應該可以作業
soup = BeautifulSoup(html_data, 'lxml')
price_range=soup.select_one('div:-soup-contains("PRICE RANGE") div').text
hotel_class=soup.select_one('#ABOUT_TAB svg[title*="bubbles"]')['title']
他們有一個 API,如果你在這個網站上有很多作業要做,那可能是值得的。代碼太糟糕了,我認為它已經值得了,但這只是我的意見
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351355.html
