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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

九州編程 2021-09-02 20:59:29
我正在嘗試做的事情:我正在嘗試編寫一個(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。


查看完整回答
反對(duì) 回復(fù) 2021-09-02
  • 1 回答
  • 0 關(guān)注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)