BeautifulSoup - 标签下缺少标签

BeautifulSoup - Missing tag under tag

所以,我想从 "h1" 标签中获取文本。我正在使用 BeutifulSoup,它工作正常,直到 "article" 标签中没有 "h1" 标签,然后我得到“'NoneType' 对象没有属性 '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'>

你应该循环遍历 articles ,这是一个列表,然后使用 find_all() 方法获取 a 标签内的所有 h1 然后添加它的 text 到 h1s。看来这就是你想要的 -

h1s = []
articles = soup.find_all("article")
for i in articles:
    for x in i.find_all('h1'):
            h1s.append(x.text)