我正在嘗試做的事情:我正在嘗試編寫一個腳本來抓取網站以獲取產品信息。目前,該程序使用 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。
添加回答
舉報
0/150
提交
取消