【问题标题】:BeautifulSoup - Missing tag under tagBeautifulSoup - 标签下缺少标签
【发布时间】: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


    【解决方案1】:

    你应该只循环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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多