gpt4 book ai didi

python - BeautifulSoup 不能使用 if is None then continue 语句来避免 'NoneType' object is not subscriptable Type Error

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:26 25 4
gpt4 key购买 nike

代码如下:

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

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

最佳答案

如果仅在 href 之后使用 select 并使用 href 指定带有子元素的父类,则取决于您还想用 block 做什么> 使用后代组合器的属性

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

关于python - BeautifulSoup 不能使用 if is None then continue 语句来避免 'NoneType' object is not subscriptable Type Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com