第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

Python:“如果 i.find('a')['id'] 不是 None:

Python:“如果 i.find('a')['id'] 不是 None:

九州編程 2021-09-02 20:59:29
我正在嘗試做的事情:我正在嘗試編寫一個腳本來抓取網站以獲取產品信息。目前,該程序使用 for 循環(huán)來獲取產品價格和唯一 ID。for 循環(huán)包含兩個 if 語句以阻止它抓取 NoneType。import requestsfrom bs4 import BeautifulSoupdef average(price_list):    return sum(price_list) / len(price_list)# Requests search data from Websitepage_link = 'URL'page_response = requests.get(page_link, timeout=5)  # gets the webpage (search) from Websitepage_content = BeautifulSoup(page_response.content, 'html.parser')  # turns the webpage it just retrieved into a BeautifulSoup-object# Selects the product listings from page content so we can work with theseproduct_listings = page_content.find_all("div", {"class": "unit flex align-items-stretch result-item"})prices = []  # Creates a list to add the prices touids = [] # Creates a list to store the unique idsfor product in product_listings:## UIDS     if product.find('a')['id'] is not None:        uid = product.find('a')['id']        uids.append(uid)# PRICES    if product.find('p', class_ = 'result-price man milk word-break') is not None:# assures that the loop only finds the prices        price = int(product.p.text[:-2].replace(u'\xa0', ''))  # makes a temporary variable where the last two chars of the string (,-) and whitespace are removed, turns into int        prices.append(price)  # adds the price to the list問題:上if product.find('a')['id'] is not None:,我得到一個Exception has occurred: TypeError'NoneType' object is not subscriptable.不管是誰,如果我跑了print(product.find('a')['id']),我就會得到我正在尋找的價值,這讓我很困惑。這不意味著錯誤不是 NoneType 嗎?此外,if product.find('p', class_ = 'result-price man milk word-break') is not None:工作完美無缺。我試過的:我試過分配if product.find('p', class_ = 'result-price man milk word-break')給一個變量,然后在 for 循環(huán)中運行它,但這不起作用。我也做了我應得的谷歌搜索,但沒有占上風。問題可能是我對編程比較陌生,不知道要搜索什么,但我仍然找到了很多似乎與相關問題有關的答案,但這在我的工作中不起作用代碼。任何幫助將不勝感激!
查看完整描述

1 回答

?
米脂

TA貢獻1836條經驗 獲得超3個贊

只需做一個中間步驟:


res = product.find('a')


if res is not None and res['id'] is not None:

    uids.append(res['id'])

這樣,如果 findNone由于未找到該項目而返回,則您最終不會嘗試下標 NoneType。


查看完整回答
反對 回復 2021-09-02
  • 1 回答
  • 0 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

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

公眾號

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