2 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
最簡(jiǎn)單的方法是:
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貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
您可以在嘗試訪問(wèn)text屬性之前測(cè)試變量是否為 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)
添加回答
舉報(bào)