使用BeautifulSoup4从网页获取文本时,获取“None”和“NoneType object…”错误

2024-09-27 19:18:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从BBC体育版上调出主要标题(目前是:“温格预测‘活跃’的一月”)。ID是'lead caption',它位于<h2><a>标记中。我在用Python。你知道吗

from bs4 import BeautifulSoup
import urllib2
url = urllib2.urlopen("http://www.bbc.co.uk/sport/football/teams/arsenal")
soup=BeautifulSoup(url.read())
#Things I've tried
headline=soup.find('a', attrs={'id': 'lead-caption'})
print headline
#The above prints 'None'
headline1=soup.find('lead-caption').getText()
print headline1
#The above print "'NoneTpye' Object has no attirbute 'getText'
tag = soup.a
tag ['id'] = 'lead-caption'
type(tag)
print tag.string
#Error: NoneType object does not support item assignment

任何帮助都将不胜感激。谢谢:)


Tags: theimportidurltagfindurllib2above
1条回答
网友
1楼 · 发布于 2024-09-27 19:18:54

你的代码几乎是正确的,你在错误的元素中寻找,这就是为什么你得到None,它应该是div

headline=soup.find('div', attrs={'id': 'lead-caption'})
headline_text=headline.find('a').getText()
print headline_text

输出:

Wenger predicts 'active' January

相关问题 更多 >

    热门问题