
在进行网页数据抓取(web scraping)时,我们常常会遇到目标网站结构不完全一致的情况。例如,某些数据记录可能包含所有预期的字段,而另一些记录则可能缺少部分字段。如果我们在抓取时未能妥善处理这些缺失的元素,很可能导致最终收集到的数据出现错位,从而影响数据的准确性和可用性。
本教程将以抓取漫画店名称及其网站为例,演示如何使用requests和BeautifulSoup库,结合pandas和numpy,构建一个健壮的抓取脚本,以确保即使在部分信息缺失的情况下,也能正确地将数据对齐。
在开始之前,请确保您已经安装了以下Python库:
您可以使用pip安装它们:
pip install requests beautifulsoup4 pandas numpy
解决数据错位的关键在于按记录迭代。而不是分别抓取所有名称和所有网站,我们应该找到一个能够代表单个数据记录(例如,单个商店)的父级HTML元素,然后在这个父级元素内部提取该记录的所有相关信息。如果某个信息不存在,我们则明确地用一个占位符(如np.nan)来表示。
对于本例,我们观察目标网页结构,发现每个商店的信息都被包裹在一个div标签中,其class为CslsLocationItem。这将是我们迭代的基石。
首先,我们需要发送HTTP请求获取主页面的HTML内容,并使用BeautifulSoup进行解析。
import requests import numpy as np import pandas as pd from bs4 import BeautifulSoup # 目标URL url = "https://www.comicshoplocator.com/StoreLocatorPremier?query=75077&showCsls=true" # 发送请求并解析HTML response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") # 用于存储所有商店数据的列表 all_data = []
接下来,我们将遍历所有CslsLocationItem元素。对于每个商店,我们将执行以下步骤:
for shop in soup.select(".CslsLocationItem"):
# 1. 提取商店名称
# 使用.select_one()确保只获取第一个匹配项
name_tag = shop.select_one(".LocationName")
name = name_tag.text if name_tag else np.nan # 确保元素存在
# 2. 检查是否存在商店详情页链接
profile_link_tag = shop.select_one(".LocationShopProfile a")
website_url = np.nan # 默认网站链接为NaN
if profile_link_tag:
# 如果存在详情页链接,则构建完整URL并访问
profile_page_url = "https://www.comicshoplocator.com" + profile_link_tag["href"]
profile_response = requests.get(profile_page_url)
profile_soup = BeautifulSoup(profile_response.content, "html.parser")
# 3. 在详情页中提取网站链接
web_link_tag = profile_soup.select_one(".StoreWeb a")
if web_link_tag:
website_url = web_link_tag["href"]
# else: website_url 保持为 np.nan
# 将名称和网站URL作为元组添加到列表中
all_data.append((name, website_url))代码解析与改进点:
抓取完所有数据后,我们可以将其转换为一个结构化的Pandas DataFrame,以便于后续的数据分析和存储。
# 使用抓取到的数据创建DataFrame df = pd.DataFrame(all_data, columns=["Name", "Website"]) # 打印结果(以Markdown表格形式,便于查看) print(df.to_markdown(index=False))
预期输出示例:
| Name | Website | |:--------------------------|:---------------------------------| | TWENTY ELEVEN COMICS | http://WWW.TWENTYELEVENCOMICS.COM | | READ COMICS | nan | | BOOMERANG COMICS | http://www.boomerangcomics.com | | MORE FUN COMICS AND GAMES | http://www.facebook.com/morefuncomics | | MADNESS COMICS & GAMES | http://www.madnesscomicsandgames.com | | SANCTUARY BOOKS AND GAMES | nan |
可以看到,READ COMICS和SANCTUARY BOOKS AND GAMES由于没有对应的网站信息,其Website列被正确地填充为nan,而其他商店的数据则准确对齐。
import requests
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
def scrape_comic_shops(query_zip_code="75077"):
"""
抓取指定邮政编码区域的漫画店名称和网站。
Args:
query_zip_code (str): 查询的邮政编码。
Returns:
pd.DataFrame: 包含漫画店名称和网站的DataFrame。
如果网站不存在,则对应值为np.nan。
"""
base_url = "https://www.comicshoplocator.com"
search_url = f"{base_url}/StoreLocatorPremier?query={query_zip_code}&showCsls=true"
try:
response = requests.get(search_url)
response.raise_for_status() # 检查HTTP请求是否成功
except requests.exceptions.RequestException as e:
print(f"请求主页面失败: {e}")
return pd.DataFrame(columns=["Name", "Website"])
soup = BeautifulSoup(response.content, "html.parser")
all_data = []
# 遍历每个商店的父容器
for shop in soup.select(".CslsLocationItem"):
name_tag = shop.select_one(".LocationName")
name = name_tag.text.strip() if name_tag else np.nan
profile_link_tag = shop.select_one(".LocationShopProfile a")
website_url = np.nan
if profile_link_tag and 'href' in profile_link_tag.attrs:
profile_path = profile_link_tag["href"]
profile_page_url = f"{base_url}{profile_path}"
try:
profile_response = requests.get(profile_page_url)
profile_response.raise_for_status()
profile_soup = BeautifulSoup(profile_response.content, "html.parser")
web_link_tag = profile_soup.select_one(".StoreWeb a")
if web_link_tag and 'href' in web_link_tag.attrs:
website_url = web_link_tag["href"].strip()
except requests.exceptions.RequestException as e:
print(f"请求商店详情页 {profile_page_url} 失败: {e}")
# 如果请求失败,website_url 保持为 np.nan
all_data.append((name, website_url))
df = pd.DataFrame(all_data, columns=["Name", "Website"])
return df
if __name__ == "__main__":
df_result = scrape_comic_shops(query_zip_code="75077")
print("抓取结果:")
print(df_result.to_markdown(index=False))本教程演示了如何使用requests和BeautifulSoup库,通过“按记录迭代”和“条件式提取”的策略,有效地解决了网页抓取中因元素缺失导致的数据错位问题。通过将每个记录的名称和其对应的(可能缺失的)网站信息作为一个整体进行处理,并利用numpy.nan填充缺失值,我们能够构建一个健壮且输出数据准确对齐的抓取脚本。掌握这些技巧对于任何需要从非结构化网页数据中提取结构化信息的任务都至关重要。
以上就是使用BeautifulSoup处理缺失元素:构建健壮的网页数据抓取教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号