[英]BeautifulSoup search on beautifulsoup result?
搜尋旅館網站以檢索標題和價格。 “ hotelInfo”是保存有趣內容的div
。
對我來說,我只想在此div
上執行操作就很有意義。 我的代碼如下-
from bs4 import BeautifulSoup
import requests
response = requests.get("http://$hotelurlhere.com")
soup = BeautifulSoup(response.text)
hotelInfo = soup.select('div.hotel-wrap')
hotelTitle = soup.find_all('h3', attrs={'class': 'p-name'})
hotelNameList = []
hotelPriceList = []
for hotel in hotelInfo:
for title in hotelTitle:
hotelNameList.append(title.text)
說hotelTitle應該是上述hotelInfo上的Beautifulsoup搜索更有意義。 但是當我嘗試這個
hotelTitle = hotelInfo.find_all('h3', attrs={'class': 'p-name'})
錯誤信息:
Traceback (most recent call last):
File "main.py", line 8, in <module>
hotelTitle = hotelInfo.find_all('h3', attrs={'class': 'p-name'})
AttributeError: 'list' object has no attribute 'find_all'
返回了與列表元素不具有“ find_all”屬性有關的錯誤。 我了解這是因為hotelInfo是返回的列表元素。 我已經搜索了有關檢查此列表中的h3
信息的正確方法的信息,但沒有成功。
做這個的最好方式是什么? 我應該不能將hoteTitle設置為hotelInfo.find_all而不是只設置soup.find_all嗎?
如錯誤消息清楚地表明,沒有可在list
對象中調用的find_all()
方法。 在這種情況下,您應該在list
單個成員上調用find_all()
,假設您需要div.hotel-wrap
以及相應的h3
一些信息:
for hotel in hotelInfo:
hotelTitle = hotel.find_all('h3', attrs={'class': 'p-name'})
如果只需要h3
元素,則可以組合兩個選擇器直接獲取它們,而不hotelInfo
查找hotelInfo
:
hotelTitle = soup.select('div.hotel-wrap h3.p-name')
對於hotelinfo,郵政編碼中的酒店標題(hotelinfos,酒店標題):Data = {'hotelinfo':hotelinfo.get_text(),}打印(數據)
像那樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.