Python BeautifulSoup-标记下缺少标记

Python BeautifulSoup-标记下缺少标记,python,tags,beautifulsoup,Python,Tags,Beautifulsoup,所以,我想从“h1”标签中获取文本。我使用的是BeutifulSoup,它工作正常,直到“article”标记中没有“h1”标记,然后我得到“'NoneType'对象没有属性'contents'错误。 代码如下: from bs4 import BeautifulSoup page = "<article> <a href="http://something"> </a> (missing "h1") <a hr

所以,我想从“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)
从bs4导入美化组
第页=
“(缺少“h1”)
"
汤=美汤(第页,“lxml”)
h1s=[]
文章=汤。全部查找(“文章”)
对于范围(1,len(文章))中的i:
h1s.append(articles[i].h1.contents)
这些是当我检查带有h1标记和不带h1标记的行时的消息

type(articles[0].h1) 
<type 'NoneType'>
type(articles[1].h1)
<class 'bs4.element.Tag'>
类型(文章[0].h1)
类型(文章[1].h1)

您只需循环查看
文章,这是一个列表,然后使用
find_all()
方法获取
a
标记中的所有
h1
,然后将其
文本添加到h1s中。似乎这就是您想要的-

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