亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果頁面上不存在元素,則跳過項目

如果頁面上不存在元素,則跳過項目

偶然的你 2022-04-27 16:27:04
這是我的整個代碼。response = requests.get("https://www.zomato.com/san-francisco/restaurants?q=restaurants&page=" + str(i),headers=headers)content = response.contentbs = BeautifulSoup(content, "html.parser")zomato_containers = bs.find_all("div", {"class": "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]').text      numVotes = numVotes[1] if len(numVotes) > 1 else numVotes[0]    print("restaurant_title: ", title)    print("numVotes: ", numVotes)我收到一個錯誤:“numVotes = zomato_container.select_one('[class^=rating-votes-div]').text AttributeError: 'NoneType' 對象沒有屬性 'text'”我非??隙ㄟ@是因為頁面上的某些元素不存在。我試圖跳過這些元素,但無法弄清楚如何。非常感謝。我非常感激。
查看完整描述

2 回答

?
慕尼黑5688855

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)



查看完整回答
反對 回復 2022-04-27
?
紫衣仙女

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)


查看完整回答
反對 回復 2022-04-27
  • 2 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號