Python 'NoneType' 对象没有属性 'text'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34434300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:58:36  来源:igfitidea点击:

'NoneType' object has no attribute 'text'

pythonbeautifulsoupbs4

提问by Steason Tee

How should I extract "£70,004" text in dd, omitting "Investment sought" text which in dt.

我应该如何在 dd 中提取“£70,004”文本,省略 dt 中的“寻求投资”文本?

from bs4 import BeautifulSoup
import urllib2

url="https://www.seedrs.com/tanorganic"
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read(), "html.parser")

target = soup.find("dl", class_="investment_sought").text

print target

figure = soup.find("dd", class_="investment_sought").text

print figure

result :

结果 :

Investment

sought:

£70,004

Traceback (most recent call last):
  File "testing.py", line 12, in <module>
    figure = soup.find("dd", class_="investment_sought").text
AttributeError: 'NoneType' object has no attribute 'text'

采纳答案by Avinash Raj

I suggest you to change the last 4 lines like below since there isn't a ddtag with investment_soughtas class attrib value. Remove the first printstmt if you don't want..

我建议您像下面这样更改最后 4 行,因为没有dd带有investment_soughtas 类属性值的标签。print如果您不想要,请删除第一个stmt。

target = soup.find("dl", class_="investment_sought")
print target.text
figure = target.find("dd").text
print figure

Example:

例子:

>>> from bs4 import BeautifulSoup
>>> import urllib2
>>> url="https://www.seedrs.com/tanorganic"
>>> page = urllib2.urlopen(url)
>>> soup = BeautifulSoup(page.read(), "html.parser")
>>> target = soup.find("dl", class_="investment_sought")
>>> print target.text


Investment

sought:

£70,004

>>> figure = target.find("dd").text
>>> print figure
£70,004
>>>