Airbnb多页面Selenium爬虫问题排查与优化咨询
Airbnb 爬虫问题解决方案
1. 确保全量抓取所有页面房源链接
- 处理无限滚动加载:Airbnb列表页多采用滚动加载,循环执行滚动并等待新内容加载,直到无新房源出现。示例代码:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC seen_links = set() last_height = driver.execute_script("return document.body.scrollHeight") while True: # 抓取当前页面所有房源链接 listings = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div[data-testid="listing-card"] a')) ) for listing in listings: link = listing.get_attribute('href') if link: seen_links.add(link) # 滚动到底部 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 等待新内容加载 WebDriverWait(driver, 5).until( lambda d: d.execute_script("return document.body.scrollHeight") > last_height ) new_height = driver.execute_script("return document.body.scrollHeight") # 判断是否到达页面底部 if new_height == last_height: break last_height = new_height - 去重机制:用集合
set()存储链接,自动过滤重复项。 - 稳定定位房源元素:优先使用
data-testid属性选择器(如div[data-testid="listing-card"]),避免依赖易变的class名称。 - 异常捕获:在链接提取环节加入
try-except,防止单个元素加载失败中断整个页面抓取。
2. 优化房源详情提取稳定性
- 强制显式等待:针对每个详情元素,用
WebDriverWait等待其加载完成,替代全局隐式等待。示例:# 提取标题 title = WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'h1[data-testid="listing-title"]')) ).text.strip() # 提取价格 price = WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'span[data-testid="price-and-discounted-price"]')) ).text.strip() - 优先用稳定定位器:优先选择
data-testid、id等不易变更的属性,避免使用动态生成的class或复杂XPATH。 - 处理弹窗干扰:进入详情页后,先检查是否存在登录/提示弹窗,若存在则点击关闭按钮(如
button[data-testid="modal-close"])。 - 重试机制:对易失败的提取操作加入重试逻辑,比如失败后等待1秒再重试,最多重试3次。
- 验证页面加载状态:通过
driver.execute_script("return document.readyState") == "complete"确认页面完全加载后再提取数据。
3. 动态内容与分页的更优方案
- 优先使用非官方API:Airbnb的搜索结果可通过其内部API获取JSON格式数据,无需渲染页面,效率和稳定性远高于Selenium。可通过浏览器开发者工具抓包分析接口参数(如地区ID、日期、分页参数),直接用
requests请求接口。 - Selenium + BeautifulSoup组合:用Selenium加载完页面后,获取
driver.page_source,再用BeautifulSoup解析HTML,减少Selenium的DOM操作次数,提升效率。 - 无头浏览器模式:启用Chrome无头模式,降低资源占用,同时设置固定窗口大小避免元素定位偏移:
from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--headless=new") chrome_options.add_argument("--window-size=1920,1080") driver = webdriver.Chrome(options=chrome_options) - 智能分页/滚动策略:
- 若页面有分页按钮,判断按钮是否处于禁用状态(如class包含
disabled),禁用则停止分页;可用则点击并等待页面加载。 - 无限滚动时,可加入随机等待时间(1-3秒),模拟人类操作,降低反爬风险。
- 若页面有分页按钮,判断按钮是否处于禁用状态(如class包含
- 反爬应对:设置随机User-Agent,添加请求间隔(2-5秒),必要时使用代理IP;避免连续快速操作,模拟随机滚动、点击等行为。
- 实时数据持久化:抓取过程中实时将数据写入CSV/JSON文件,避免程序崩溃导致数据丢失。
内容的提问来源于stack exchange,提问作者Nizar Baddou
相关产品推荐
相关产品推荐

