
在进行网页数据抓取时,常见的问题之一是当某些字段(例如,一个商店的网站链接)并非对所有记录都可用时,数据在最终的表格或dataframe中可能会出现错位。原始的抓取逻辑可能倾向于分别处理不同类型的数据(如先抓取所有商店名称,再抓取所有网站链接),如果网站链接的数量少于商店名称的数量,或者链接与名称的顺序因缺失项而被打乱,就会导致数据列之间无法正确匹配。
例如,在一个抓取商店名称和网站的场景中,如果某些商店没有提供网站链接,而抓取代码没有妥善处理这种情况,那么在构建最终的DataFrame时,网站列的数据就会向上“漂移”,错误地匹配到不属于它的商店,从而导致数据完整性受损。
解决此类问题的核心在于确保每个“逻辑单元”(在本例中是每个商店)的所有相关数据都在同一个迭代周期内被处理和收集。这意味着我们需要找到一个能代表每个独立记录的父级HTML元素,然后在这个父级元素的范围内,尝试提取所有所需的信息。如果某个信息不存在,我们应明确地为其指定一个缺失值(如 None 或 numpy.nan),而不是简单地跳过,以保持数据的对齐。
以下是实现这一策略的详细步骤和示例代码:
首先,我们需要 requests 库来发送HTTP请求,BeautifulSoup 来解析HTML,以及 pandas 和 numpy 来处理数据和表示缺失值。
import requests import numpy as np import pandas as pd from bs4 import BeautifulSoup
指定目标URL,使用 requests.get() 获取页面内容,然后用 BeautifulSoup 进行解析。
url = "https://www.comicshoplocator.com/StoreLocatorPremier?query=75077&showCsls=true" response = requests.get(url) response.raise_for_status() # 检查请求是否成功 soup = BeautifulSoup(response.content, "html.parser")
关键一步是识别并迭代每个代表一个独立记录的父级HTML元素。通过观察网页结构,我们发现每个商店的信息都包含在 div 标签且 class 为 CslsLocationItem 的元素中。
all_data = [] # 用于存储所有抓取到的数据
for shop in soup.select(".CslsLocationItem"):
# 在此循环内部处理每个商店的所有信息
# ...在每个 shop 元素内部,我们可以使用 select_one() 方法来精确地选择商店名称。select_one() 会返回第一个匹配的元素,如果没有匹配项则返回 None,这对于处理可能缺失的元素非常有用。
name = shop.select_one(".LocationName").text.strip() # .text.strip() 获取文本并去除空白接下来,我们需要检查当前商店是否有“Shop Profile”链接。如果存在,我们才需要访问其详情页以获取更多信息。
profile_link_element = shop.select_one(".LocationShopProfile a")
website_url = np.nan # 默认网站链接为NaN
if profile_link_element:
profile_url_suffix = profile_link_element["href"]
full_profile_url = "https://www.comicshoplocator.com" + profile_url_suffix
# 访问商店详情页
profile_response = requests.get(full_profile_url)
profile_response.raise_for_status()
profile_soup = BeautifulSoup(profile_response.content, "html.parser")
# 从详情页中提取网站链接
store_web_element = profile_soup.select_one(".StoreWeb a")
if store_web_element:
website_url = store_web_element["href"]在每个循环结束时,将当前商店的名称和网站链接(无论是否找到)作为一个元组添加到 all_data 列表中。
all_data.append((name, website_url))
所有数据收集完毕后,使用 all_data 列表创建一个Pandas DataFrame,并指定列名。
df = pd.DataFrame(all_data, columns=["Name", "Website"])
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"
# 发送请求并解析主页面
try:
response = requests.get(url)
response.raise_for_status() # 检查HTTP请求是否成功
soup = BeautifulSoup(response.content, "html.parser")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
exit()
all_data = []
# 迭代每个商店的父级元素
for shop in soup.select(".CslsLocationItem"):
name = shop.select_one(".LocationName").text.strip()
profile_link_element = shop.select_one(".LocationShopProfile a")
website_url = np.nan # 默认网站链接为NaN
if profile_link_element:
profile_url_suffix = profile_link_element["href"]
full_profile_url = "https://www.comicshoplocator.com" + profile_url_suffix
try:
# 访问商店详情页
profile_response = requests.get(full_profile_url)
profile_response.raise_for_status()
profile_soup = BeautifulSoup(profile_response.content, "html.parser")
# 从详情页中提取网站链接
store_web_element = profile_soup.select_one(".StoreWeb a")
if store_web_element:
website_url = store_web_element["href"]
except requests.exceptions.RequestException as e:
print(f"访问商店详情页 {full_profile_url} 失败: {e}")
# 如果详情页访问失败,网站链接仍为NaN
all_data.append((name, website_url))
# 创建Pandas DataFrame
df = pd.DataFrame(all_data, columns=["Name", "Website"])
# 打印结果
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 |
通过采用统一迭代父级元素并在单个循环内处理所有子元素的策略,并结合条件判断来优雅地处理缺失数据,我们可以有效地解决网页抓取中数据错位的问题。这种方法确保了数据的完整性和对齐性,为后续的数据分析和处理奠定了坚实的基础。在实际应用中,结合健壮的错误处理和良好的实践,可以构建出高效且可靠的网页数据抓取工具。
以上就是解决网页数据抓取中数据错位问题的教程:统一处理与缺失值管理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号