首页 > 解决方案 > Python - 带有 BeautifulSoup 的网络抓取 pubmed.gov 摘要 - 出现非类型错误

问题描述

我正在从pubmed.gov抓取摘要,它在大多数情况下都在工作,除了没有文本的摘要。我尝试了一个 IF 语句,但我显然没有做对。我怎样才能做到这一点并让它跳过没有抽象文本的网址?我提供了一个发生这种情况的 URL。

我收到此错误:AttributeError: 'NoneType' object has no attribute 'find'

提前致谢!

import requests
from bs4 import BeautifulSoup

listofa_urls = ['https://www.ncbi.nlm.nih.gov/pubmed/31103571']

for th in listofa_urls:

    response = requests.get(th)
    soup = BeautifulSoup(response.content, 'html.parser')

    if (soup.find(class_='abstr').find('div') is not None):
       div_ = soup.find(class_='abstr').find('div')
       if div_.find('h4'):
           h4_ = div_.find_all('h4')
           p_ = div_.find_all('p')
       else:
           h4_ = soup.find(class_='abstr').find_all('h3')
           p_ = soup.find(class_='abstr').find_all('p')

       mp = list(map(lambda x, y: [x.get_text(),y.get_text()], h4_, p_))
       print(mp)

标签: pythontextweb-scrapingbeautifulsouppubmed

解决方案


如评论中所述,您不能.find()对 None 执行任何操作,因此只需检查第一个是否find找到任何内容。

只需删除第二个find

if (soup.find(class_='abstr').find('div') is not None):

变成

if (soup.find(class_='abstr') is not None)

推荐阅读