2 回答
TA贡献1848条经验 获得超2个赞
最简单的方法是:
for zomato_container in zomato_containers:
title = zomato_container.find("a", {"class": "result-title"}).get_text()
try:
numVotes = zomato_container.select_one('[class^=rating-votes-div]').text
numVotes = numVotes[1] if len(numVotes) > 1 else numVotes[0]
except AttributeError:
continue
print("restaurant_title: ", title)
print("numVotes: ", numVotes)
TA贡献1839条经验 获得超15个赞
您可以在尝试访问text属性之前测试变量是否为 None
import requests
from bs4 import BeautifulSoup as bs
i = 1
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get("https://www.zomato.com/san-francisco/restaurants?q=restaurants&page=" + str(i),headers=headers)
content = response.content
soup = bs(content, "html.parser")
zomato_containers = soup.select('.search-snippet-card')
for zomato_container in zomato_containers:
title = zomato_container.find("a", {"class": "result-title"}).get_text()
numVotes = zomato_container.select_one('[class^=rating-votes-div]')
if numVotes is None:
numVotes = 'N/A'
else:
numVotes = numVotes.text.strip()
print("restaurant_title: ", title)
print("numVotes: ", numVotes)
添加回答
举报