【问题标题】:Beautiful Soup find_all error when cant find tag找不到标签时,Beautiful Soup find_all 错误
【发布时间】:2020-08-20 14:38:02
【问题描述】:

正如标题所说,我需要一些方法来检查 find_all 是否返回值。

第一次尝试。这没问题

cmslink =  'https://www.cms.gov/research-statistics-data-and-systemsstatistics-trends-and-reportsmcradvpartdenroldatamonthly-pdp/pdp-enrollment-scc-2020-01'
content, _ = http_request_get(url=cmslink,payload={'t':''},parse=True)
table = [a['href'] for a in content.find("ul", class_="field__items").find_all('a')]

第二次尝试。此尝试失败,因为该页面没有它正在寻找的链接

cmslink = 'https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/MCRAdvPartDEnrolData/Monthly-Contract-and-Enrollment-Summary-Report-Items/Contract-Summary-2017-04'
content, _ = http_request_get(url=cmslink,payload={'t':''},parse=True)
table = [a['href'] for a in content.find("ul", class_="field__items").find_all('a')]

我的问题是如何在执行设置表变量的行之前检查一些方法。

我遇到的错误没有多大帮助,我通过检查页面发现链接丢失了。当我在没有链接丢失的页面上运行它时,它运行良好。

AttributeError: 'NoneType' object has no attribute 'find_all'

【问题讨论】:

  • 两种方式。 1)你可以用一个试试,除了。 2)在尝试获取href属性之前检查find_all('a')的结果长度是否大于0。
  • 好的,斯里。同意,但是我无法运行当前行的语法是什么,因为它失败了。我的 python 语法仍在进行中

标签: python web-scraping beautifulsoup


【解决方案1】:

正如斯里所说:

try:
    table = [a['href'] for a in content.find("ul", class_="field__items").find_all('a')]
except AttributeError:
    print( 'No class_="field__items" found')

或:

a_list = content.find("ul", class_="field__items")
if len(a_list != 0):
    table = [a['href'] for a in a_list.find_all('a')]

【讨论】:

  • 好的,第一个成功了,谢谢。第二个不起作用,因为它尝试执行失败
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 2021-09-03
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多