Selenium爬虫缺失值错误处理与数据漏爬问题咨询
爬虫问题修复方案
问题1:联系方式错位修复
问题原因
原有代码是分别抓取全页所有姓名、地址、手机号三类独立元素,若部分卡片无手机号,三类元素的列表长度会不一致,zip配对时自然会出现错位。
修复逻辑
先定位每张联系卡的外层公共容器(需根据实际页面结构替换容器的class名,示例假设容器class为pflist-item),逐张遍历卡片,在单张卡片内部单独查找三类字段,找不到手机号时直接填充not available,确保每张卡片的三个字段一一对应。
问题2:漏爬数据修复
问题原因
确实是页面加载速度差异导致的,原有代码没有等待逻辑,页面元素还未完全渲染完成就执行了抓取操作,就会出现漏抓的情况。
修复逻辑
使用selenium的显式等待替代无等待/固定时长死等,抓取前先等待所有联系卡加载完成,点击下一页后等待页面刷新完成再进入下一轮抓取,避免在元素未加载完成时执行操作。
修改后完整代码
import pandas as pd from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC df = pd.DataFrame(columns=['Name', 'Address', 'Contact']) driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # 显式等待对象,最长等待10秒,可根据页面加载速度调整 wait = WebDriverWait(driver, 10) url = 'http://www.website.com' # 注意补全http/https协议 driver.get(url) for page in range(200): print(f'开始抓取第{page+1}页') # 等待所有联系卡加载完成再执行抓取 cards = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'pflist-item'))) temp_list = [] for card in cards: # 单张卡片内提取字段,不存在则填充占位符 try: name = card.find_element(By.CLASS_NAME, 'pflist-itemtitle').text except: name = 'not available' try: address = card.find_element(By.CLASS_NAME, 'pflist-address').text except: address = 'not available' try: contact = card.find_element(By.CSS_SELECTOR, "a[href*='tel:']").text except: contact = 'not available' temp_list.append({'Name':name, 'Address':address, 'Contact':contact}) # 合并数据,pandas高版本已弃用append方法,改用concat temp_df = pd.DataFrame(temp_list) df = pd.concat([df, temp_df], ignore_index=True) print(f'第{page+1}页抓取完成,累计数据{len(df)}条') # 翻页逻辑 driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.END) next_btn = wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, 'Next »'))) # 点击下一页前先记录当前页的元素标识,用于判断页面是否跳转完成 old_card = driver.find_element(By.CLASS_NAME, 'pflist-itemtitle') next_btn.click() # 等待旧页元素失效,确认页面已刷新后再进入下一轮循环 wait.until(EC.staleness_of(old_card)) # 可根据需要添加导出逻辑,例:df.to_excel('爬取结果.xlsx', index=False) driver.quit()
内容的提问来源于stack exchange,提问作者komskisp
相关产品推荐
相关产品推荐

