【问题标题】:AttributeError: 'NoneType' object has no attribute 'get_text' python 3xAttributeError:“NoneType”对象没有属性“get_text”python 3x
【发布时间】:2019-03-18 22:30:48
【问题描述】:

我一直在为这段代码苦苦挣扎:

def MainPageSpider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'url' + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = bs(plain_text, 'html.parser')
        for link in soup.findAll(attrs={'class':'col4'}):
            href = 'url' + link.a['href']
            title = link.span.text

            PostPageItems(href)
        page += 1


def PostPageItems(post_url):
    source_code = requests.get(post_url)
    plain_text = source_code.text
    soup = bs(plain_text, 'html.parser')
    for items in soup.findAll(attrs={'class':'container'}):
        title2 = items.find('h1', {'class':'title'}).get_text()

        print(title2)




MainPageSpider(1)

每次我尝试从“h1”获取文本时都会收到此错误:

Traceback (most recent call last):
  File "Xfeed.py", line 33, in <module>
    MainPageSpider(1)
  File "Xfeed.py", line 17, in MainPageSpider
    PostPageItems(href)
  File "Xfeed.py", line 27, in PostPageItems
    test = title2.get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'

但是当我在没有 'get_text()' 的情况下运行它时,我会得到 'h1' HTML:

<h1 class="title">Title 1</h1>
None
None
None
None
<h1 class="title">Title 2</h1>
None
None
None
None
<h1 class="title">Title 3</h1>
None
None
None
None

我真的不明白为什么在使用title = link.span.text 时会出现此错误,我在获取文本时没有任何问题。 我只想要文字。

【问题讨论】:

  • 如果项目没有h1 条目,那么find 将返回None,这就是为什么您会在输出中看到每个h1 之间的所有Nones .你需要处理这种情况。

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

不是每个container 都有一个h1,所以只需检查是否返回了None,如果没有则打印。

for items in soup.findAll(attrs={'class':'container'}):
        title2 = items.find('h1', {'class':'title'})
        if title2:
            print(title2.text)

【讨论】:

    【解决方案2】:

    从没有get_text() 的输出看来,title2 通常是None,由于None 没有get_text() 属性,它应该会因您发布的错误而失败。您可以将其拆分为 2 个语句并添加如下检查:

    title2_item = items.find('h1', {'class':'title'})
    
    if title2_item: # Check for None
        title2 = title2_item.get_text()
        print(title2)
    

    【讨论】:

      【解决方案3】:

      使用仅选择符合条件的元素的 css 选择器重写

      for item in soup.select('.container h1.title'):
              title2 = item.text
      

      【讨论】:

        猜你喜欢
        • 2017-12-28
        • 2015-04-07
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多