python - 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)
解决方案
如评论中所述,您不能.find()
对 None 执行任何操作,因此只需检查第一个是否find
找到任何内容。
只需删除第二个find
:
if (soup.find(class_='abstr').find('div') is not None):
变成
if (soup.find(class_='abstr') is not None)
推荐阅读
- angular - 如何监视在角度 7 中单击的 dom 用户
- c# - WPF - 列表绑定未加载数据源
- image-processing - SciLab:在 imshow 窗口中返回鼠标单击位置
- javascript - 地图显示键,而不仅仅是值
- google-data-studio - DataStudio 社区可视化可以访问图表调色板吗?
- node.js - 在 Node.js 中更改 JSON 对象中的字段
- javascript - PHP 检查 cookie 是否存在、等于 NULL 或存在
- python - Fill in data elided with "..." in output from pandas.DataFrame.corr()
- django - 将 SSL 与 Gunicorn/Django/Nginx 应用程序一起使用时出现混合内容错误
- python - Pytorch 索引