抓取网站会呈现空的 CSV

问题描述 投票:0回答:1

这个网站(https://oig.hhs.gov/reports-and-publications/all-reports-and-publications/)列出了各个报告,我正在尝试使用 python/BS 来抓取它们。

我正在尝试使用以下代码来抓取标题、审计、机构和日期。

但它会呈现一个空的 CSV。关于我需要在代码中修改什么内容有什么建议吗?

import requests
from bs4 import BeautifulSoup
import csv
 
url = "https://oig.hhs.gov/reports-and-publications/all-reports-and-publications/"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
 
reports = soup.find_all("div", class_="media")
 
report_data = []
 
for report in reports:
    title = report.find("h3").get_text(strip=True)
    audit = report.find("span", class_="audit").get_text(strip=True) if report.find("span", class_="audit") else "N/A"
    agency = report.find("span", class_="agency").get_text(strip=True) if report.find("span", class_="agency") else "N/A"
    date = report.find("span", class_="date").get_text(strip=True) if report.find("span", class_="date") else "N/A"
     
    report_data.append({
        "Title": title,
        "Audit": audit,
        "Agency": agency,
        "Date": date
    })
 
# Export to CSV
csv_file = "reports_data.csv"
with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
    writer = csv.DictWriter(file, fieldnames=["Title", "Audit", "Agency", "Date"])
    writer.writeheader()
    for data in report_data:
        writer.writerow(data)
 
print(f"Data exported to {csv_file}")
python web-scraping beautifulsoup
1个回答
0
投票

我不知道你从哪里得到你的班级名称——你只是猜测吗?当我查看此页面时,没有类为

'media'
'audit'
'date'
等的元素。如果您不熟悉 HTML,任何元素都可以在其开始标记中定义各种 attributes。属性可以有(几乎)任何值——类名或任何其他属性没有标准。如果您尝试根据元素的
class
属性来定位元素,则必须在 HTML 中找到准确的类名称。您可以使用任何浏览器的开发者控制台来完成此操作。

以下代码根据类名定位报表元素,然后根据标签类型查找详细信息:

reports = soup.find_all("div", class_="usa-card__container")

for report in reports:
   title = report.find("a").get_text(strip=True)
   audit, agency, date = [e.get_text(strip=True) for e in report.find_all("dd")]
© www.soinside.com 2019 - 2024. All rights reserved.