猿问

BeautifulSoup 不能使用 if is None then continue 语句来避免

代码如下:


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")

# 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))

当 .find('a')['href'] 没有返回结果时,我希望使用 if continue 语句来避免类型错误。然而,它并没有完成这项工作。有人可以指出克服它的方法吗?


红糖糍粑
浏览 124回答 3
3回答

翻阅古今

取决于你想用块做什么,如果只有在href之后使用并使用后代组合select器指定具有子元素的父类和属性hrefimport 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")cache = [searchs['href'] for searchs in soup.select('div.kCrYT [href]')]print(''.join(cache))

Smart猫小萌

使用下面的代码从TypeError.try:    cache.append(searchs.find('a')['href'])except TypeError:    continue

胡说叔叔

不要试图在一行中放这么多:...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)
随时随地看视频慕课网APP

相关分类

Python
我要回答