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

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

BeautifulSoup 不能使用 if is None then continue 語句來避免

BeautifulSoup 不能使用 if is None then continue 語句來避免

紅糖糍粑 2022-06-22 20:38:37
代碼如下:import requestsfrom bs4 import BeautifulSoupticker='FAST'url = "https://www.google.com/search?q=nasdaq+%s+earnings+reaction+history&tbs=qdr:m"%(ticker)response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")# for searchs in soup.find_all('div', {'class':'BNeawe s3v9rd AP7Wnd'}):cache = []for searchs in soup.find_all('div', {'class':'kCrYT'}):    if searchs.find('a')['href'] is None: continue    cache.append(searchs.find('a')['href'])    print(''.join(cache))當(dāng) .find('a')['href'] 沒有返回結(jié)果時(shí),我希望使用 if continue 語句來避免類型錯(cuò)誤。然而,它并沒有完成這項(xiàng)工作。有人可以指出克服它的方法嗎?
查看完整描述

3 回答

?
翻閱古今

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊

取決于你想用塊做什么,如果只有在href之后使用并使用后代組合select器指定具有子元素的父類和屬性href


import requests

from bs4 import BeautifulSoup


ticker='FAST'

url = "https://www.google.com/search?q=nasdaq+%s+earnings+reaction+history&tbs=qdr:m"%(ticker)

response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

cache = [searchs['href'] for searchs in soup.select('div.kCrYT [href]')]

print(''.join(cache))


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
Smart貓小萌

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊

使用下面的代碼從TypeError.


try:

    cache.append(searchs.find('a')['href'])

except TypeError:

    continue


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
胡說叔叔

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊

不要試圖在一行中放這么多:


...

for searchs in soup.find_all('div'):

    tag = searchs.find('a')

    #print(searchs)

    if not tag:

        continue

    try:

        h = tag['href']

    except KeyError as e:

        continue

    print(h)


查看完整回答
反對(duì) 回復(fù) 2022-06-22
  • 3 回答
  • 0 關(guān)注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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