【发布时间】:2015-10-12 17:37:03
【问题描述】:
所以,我想从“h1”标签中获取文本。我正在使用 BeutifulSoup,它工作正常,直到“article”标签中没有“h1”标签,然后我得到“'NoneType' object has no attribute 'contents'错误。 代码如下:
from bs4 import BeautifulSoup
page =
"<article>
<a href="http://something">
</a> (missing "h1")
<a href="http://something">
</a>
</article>
<article>
<a href="http://something">
</a>
<a href="http://something">
<h1>something</h1>
</a>
</article>
<article>
<a href="http://something">
</a>
<a href="http://something">
<h1>something</h1>
</a>
</article>"
soup = BeautifulSoup(page, "lxml")
h1s = []
articles = soup.find_all("article")
for i in range(1,len(articles)):
h1s.append(articles[i].h1.contents)
这些是当我检查带有 h1 标签和没有标签的行时的消息。
type(articles[0].h1)
<type 'NoneType'>
type(articles[1].h1)
<class 'bs4.element.Tag'>
【问题讨论】:
标签: python tags beautifulsoup