【问题标题】:Getting "None" and 'NoneType object...' error when using BeautifulSoup4 to get Text from a webpage使用 BeautifulSoup4 从网页获取文本时出现“无”和“无类型对象...”错误
【发布时间】:2016-01-12 21:11:54
【问题描述】:

我正在尝试从 BBC 体育页面中提取主要标题(当前:“温格预测 ' 活跃' 1 月”)。 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

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

【问题讨论】:

    标签: python python-2.7 webpage python-2.x bs4


    【解决方案1】:

    您的代码几乎是正确的,您正在寻找错误的元素,这就是您得到None 的原因,它应该是div

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

    输出:

    Wenger 预测 1 月“活跃”

    【讨论】:

    • print 语句中使用str.strip() 去除文本周围的空白:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    相关资源
    最近更新 更多