gpt4 book ai didi

python - BeautifulSoup页面抓取时出现KeyError

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:08 24 4
gpt4 key购买 nike

我正在编写一个小型应用程序,其中涉及抓取某些固定网站。在本例中,我正在抓取 TechCrunch,但由于出现了 KeyError,而我确实不应该出现这种情况,因此陷入了困境。

这是执行爬网的代码部分:

response = urllib.request.urlopen(self.url)
soup = BeautifulSoup(response.read(), "html.parser")

chunks = soup.find_all('li', class_='river-block')
html = 'TechCrunch:'
html += '<ul>'
for c in chunks:
print(c.attrs.keys())
print(c.attrs.values())
html += '<li>'
html += c.attrs['data-sharetitle']
html += '<a href="' + c.attrs['data-permalink'] + '">Read more</a>'
html += '</li>'
html += '</ul>'

其想法是,链接和标题分别存储在 data-permalinkdata-sharetitle 属性中。现在,两个 print 语句的输出正是我所期望的:

dict_keys(['class', 'data-sharetitle', 'id', 'data-shortlink', 'data-permalink'])
dict_values([['river-block', 'crunch-network'], 'Investing In Artificial\xa0Intelligence', '1251865', 'http://tcrn.ch/1mEbmcG', 'http://techcrunch.com/2015/12/25/investing-in-artificial-intelligence/'])

但是,html += c.attrs['data-sharetitle'] 行给了我KeyError: 'data-sharetitle'。为什么?

最佳答案

并非每个具有 river-block 类的 li 元素都具有 data-sharetitle 属性。 强制存在所需的属性。替换:

chunks = soup.find_all('li', class_='river-block')

与:

chunks = soup.find_all('li', {"class": "river-block", 
"data-sharetitle": True,
"data-permalink": True})

关于python - BeautifulSoup页面抓取时出现KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34483152/

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