[英]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.