我正在嘗試做的事情:我正在嘗試編寫一個(gè)腳本來抓取網(wǎng)站以獲取產(chǎn)品信息。目前,該程序使用 for 循環(huán)來獲取產(chǎn)品價(jià)格和唯一 ID。for 循環(huán)包含兩個(gè) 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:,我得到一個(gè)Exception has occurred: TypeError'NoneType' object is not subscriptable.不管是誰,如果我跑了print(product.find('a')['id']),我就會(huì)得到我正在尋找的價(jià)值,這讓我很困惑。這不意味著錯(cuò)誤不是 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')給一個(gè)變量,然后在 for 循環(huán)中運(yùn)行它,但這不起作用。我也做了我應(yīng)得的谷歌搜索,但沒有占上風(fēng)。問題可能是我對(duì)編程比較陌生,不知道要搜索什么,但我仍然找到了很多似乎與相關(guān)問題有關(guān)的答案,但這在我的工作中不起作用代碼。任何幫助將不勝感激!
1 回答

米脂
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
只需做一個(gè)中間步驟:
res = product.find('a')
if res is not None and res['id'] is not None:
uids.append(res['id'])
這樣,如果 findNone由于未找到該項(xiàng)目而返回,則您最終不會(huì)嘗試下標(biāo) NoneType。
添加回答
舉報(bào)
0/150
提交
取消