[英]I tried lot of times to grab the data from booking.com.But i couldn't
我想從 booking.com 中抓取數據,但出現了一些錯誤,找不到任何類似的代碼。 我想刮酒店的名稱,價格等。
我已經嘗試過 beautifulSoup 4 並嘗試將數據獲取到 csv 文件。
import requests
from bs4 import BeautifulSoup
import pandas
# Replace search_url with a valid one byb visiting and searching booking.com
search_url = 'https://www.booking.com/searchresults.....'
page = requests.get(search_url)
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id = 'search_results_table' )
#print(week)
items = week.find_all(class_='sr-hotel__name')
print(items[0])
print(items[0].find(class_ = 'sr-hotel__name').get_text())
print(items[0].find(class_ = 'short-desc').get_text())
這是一個示例 URL 可以用來代替search_url
。
這是錯誤消息...
<span class="sr-hotel__name " data-et-click="
">
The Fort Printers
</span>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-44-77b38c8546bb> in <module>
11 items = week.find_all(class_='sr-hotel__name')
12 print(items[0])
---> 13 print(items[0].find(class_ = 'sr-hotel__name').get_text())
14 print(items[0].find(class_ = 'short-desc').get_text())
15
AttributeError: 'NoneType' object has no attribute 'get_text'
首先,伙計,使用請求可能真的很難,因為您必須完全模仿瀏覽器將發送的請求。 您必須使用一些嗅探工具(burp、fiddler、wireshark),或者在某些情況下,在瀏覽器上以開發人員模式查看網絡,這相對困難......
我建議你使用“selenium”,它是一個 web 驅動程序,可以讓你在嘗試抓取網站時變得輕松......在這里閱讀更多相關信息 - https://medium.com/the-andela-way/introduction- to-web-scraping-using-selenium-7ec377a8cf72
至於你的錯誤,我認為你應該使用 only.text 而不是 .get_text()
如果您考慮直接使用 getText() 方法,而不是多次使用find()
方法,它會有所幫助。
import requests
from bs4 import BeautifulSoup
import pandas
# Replace search_url with a valid one byb visiting and searching booking.com
search_url = 'https://www.booking.com/searchresults.....'
page = requests.get(search_url)
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id = 'search_results_table' )
#print(week)
items = week.find_all(class_='sr-hotel__name')
# print the whole thing
print(items[0])
hotel_name = items[0].getText()
# print hotel name
print(hotel_name)
# print without newlines
print(hotel_name[1:-1])
希望這可以幫助。 我建議閱讀更多 BeautifulSoup 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.