
本文教你如何从Beautiful Soup解析出的文本中精准提取四位数字年份(如2011、2022),结合正则表达式 r”d{4}” 实现可靠匹配,并融入实际车源爬虫流程,兼顾健壮性与初学者友好性。
本文教你如何从beautiful soup解析出的文本中精准提取四位数字年份(如2011、2022),结合正则表达式 `r”d{4}”` 实现可靠匹配,并融入实际车源爬虫流程,兼顾健壮性与初学者友好性。
在使用 Beautiful Soup 抓取汽车列表(如 carsdirect.com 的丰田二手车页)时,车型标题通常以 “2022 Toyota Corolla LE” 这类格式呈现。若目标是筛选特定年份车型(例如仅保留 “2011 Highlander”),关键一步是从文本中稳定、准确地提取年份数字——而不能依赖字符串分割或模糊关键词搜索,因为页面结构可能变化、车型名含数字(如“Camry 2.5L”)、或存在多位数里程/价格干扰。
最简洁可靠的方案是使用正则表达式匹配连续4位数字:r”d{4}”。它能精准捕获年份(如 2011, 2022),同时自动跳过 47,087(里程)、3mi(距离)等非年份数字组合。
以下是在你原有代码基础上增强的完整实现(含错误处理与年份过滤逻辑):
import requests import re from bs4 import BeautifulSoup url = "https://www.carsdirect.com/used_cars/listings/toyota" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"} page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, "html.parser") results = soup.find(id="mainWrapper") job_elements = results.find_all("div", class_="infoCell") # 目标年份(可动态配置) target_year = "2011" target_model = "highlander" for job_element in job_elements: try: # 提取标题文本(如 "2022 Toyota Corolla LE") model_element = job_element.find("p", class_="ymmListRowTitle") if not model_element or not model_element.text.strip(): continue title_text = model_element.text.strip() # ✅ 使用正则提取首个4位年份(最左优先,符合年份前置惯例) year_match = re.search(r"d{4}", title_text) if not year_match: continue extracted_year = year_match.group(0) # 提取车型名(转小写便于忽略大小写) model_name = title_text.lower() # 筛选:年份匹配 + 车型包含 "highlander" if extracted_year == target_year and target_model in model_name: ymm_element = job_element.find("p", class_="ymmListRowTrim") miles_element = job_element.find("div", class_="mileLine") price_element = job_element.find("div", class_="priceLine") print(f"✅ 匹配成功:{title_text}") print(f" 年份:{extracted_year} | 型号:{ymm_element.text.strip() if ymm_element else 'N/A'}") print(f" 里程:{miles_element.text.strip() if miles_element else 'N/A'}") print(f" 价格:{price_element.text.strip() if price_element else 'N/A'}n") except AttributeError as e: # 跳过缺失关键字段的异常条目(页面结构微调常见) continue except Exception as e: print(f"处理条目时发生未知错误:{e}") continue
关键注意事项:
- ? 不要用 re.findall(…)[0] 替代 re.search(…).group(0):findall 返回列表,空列表取 [0] 会报 IndexError;search 返回 Match 对象或 None,更安全。
- ? 年份位置不固定? r”d{4}” 自动匹配任意位置的4位数字,但汽车标题中年份几乎总在最前,因此首匹配即为年份——无需额外定位。
- ? 避免误匹配:r”[12]d{3}”(限定1xxx/2xxx)可进一步排除如 9999 等非法年份,但对当前场景非必需;若需严格校验,可追加 1990
- ? 反爬提示:示例中已添加 User-Agent 头,实际部署建议配合随机 UA、请求间隔及 session 复用,避免被封。
掌握这一模式后,你不仅能筛选 2011 Highlander,还可轻松扩展为多条件组合(如 2010–2015 SUV)、导出 CSV 或存入数据库——这是结构化网页数据清洗的第一块坚实基石。