【问题标题】:AttributeError with Requests and BeautifulSoup带有请求和 BeautifulSoup 的 AttributeError
【发布时间】:2021-03-23 17:58:16
【问题描述】:

我收到错误:AttributeError:'NoneType' 对象没有属性'find' 使用以下代码,我无法找出原因:

import requests
from bs4 import BeautifulSoup

url = "https://www.ons.gov.uk/peoplepopulationandcommunity/healthandsocialcare/causesofdeath/datasets/deathregistrationsandoccurrencesbylocalauthorityandhealthboard/2021"
r = requests.get(url)

soup = BeautifulSoup(r.text, features="html.parser")

latest_file = soup.find('div', {'class': 'margin-top-md--4 margin-bottom-sm--4 margin-bottom-md--5'})
a_class_section = latest_file.find('a', {'class': 'btn btn--primary btn--thin btn--narrow btn--small'})

print(a_class_section)

【问题讨论】:

  • 如果您提供完整的回溯会很有帮助,以便清楚在哪一行引发了错误。我已经运行了代码,我没有收到错误。
  • 您的代码对我有用。我得到<a class="btn btn--primary btn--thin btn--narrow btn--small" data-gtm-date="Latest" data-gtm-download-file="lahbtables2021week10.xlsx" data-gtm-download-type="xlsx" data-gtm-type="download-version-xlsx" href="/file?uri=/peoplepopulationandcommunity/healthandsocialcare/causesofdeath/datasets/deathregistrationsandoccurrencesbylocalauthorityandhealthboard/2021/lahbtables2021week10.xlsx" title="Download as xlsx"> xlsx (3.6 MB) </a>
  • 根据您发布的代码,latest_file 在您的机器@Sanch 上似乎是None

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

该代码不适用于旧版本的 BeautifulSoup4,但它适用于 4.9 版

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多