如何绕过 Zoopla 的 Cloudflare 防护进行合法网页抓取

如何绕过 Zoopla 的 Cloudflare 防护进行合法网页抓取

zoopla 使用 cloudflare 严格反爬,直接用 requests 易触发 403 错误;本文详解通过 selenium 模拟真实浏览器行为、隐藏自动化特征,并配合合理延时,实现稳定、低风险的数据获取。

Zoopla(zoopla.co.uk)作为英国主流房产平台,对爬虫防护极为严格——其前端默认启用 Cloudflare 的「I’m Under Attack」模式,会主动拦截非常规请求头、缺失浏览器指纹或无交互行为的 HTTP 请求。你提供的 requests 代码虽设置了 User-Agent,但缺少 Cookie 上下文、JavaScript 执行能力及关键浏览器环境信号(如 navigator.webdriver),因此被判定为自动化工具,返回 403 Forbidden。

✅ 推荐方案:使用 Selenium + ChromeOptions 深度伪装
以下为可直接运行的优化示例(需提前安装 selenium 并配置 ChromeDriver):

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 配置无痕模式 + 反检测选项
options = Options()
options.add_argument("--headless")  # 可选:无界面运行(生产环境推荐)
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(options=options)

# 关键:覆盖 navigator.webdriver 属性(Cloudflare 核心检测点)
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    'source': '''
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        });
        window.chrome = { runtime: {} };
        Object.defineProperty(navigator, 'plugins', {
            get: () => [1, 2, 3, 4, 5],
        });
    '''
})

try:
    url = "https://www.zoopla.co.uk/to-rent/property/west-midlands/handsworth/sandwell-road/b21-8nl/?q=B21%208NL&radius=1"
    driver.get(url)

    # 等待主内容区域加载(避免过早解析空 DOM)
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "div[data-testid='search-results']"))
    )

    # 获取渲染后 HTML(含 JS 动态加载内容)
    html = driver.page_source
    print("✅ 页面加载成功,状态正常")

    # 后续可用 BeautifulSoup 解析
    # from bs4 import BeautifulSoup
    # soup = BeautifulSoup(html, 'html.parser')
    # listings = soup.select("div[data-testid='search-result']")

finally:
    driver.quit()

⚠️ 重要注意事项:

造次

造次

Liblib打造的AI原创IP视频创作社区

下载

  • 遵守 robots.txt 与服务条款:Zoopla 的 robots.txt(https://www.php.cn/link/b0dfd1bbadca4092f9d14d7a74085df0)明确禁止抓取大部分房源数据,商业用途需获书面授权;本教程仅限学习、研究及个人非分发用途。
  • 频率控制是关键:即使伪装完善,高频请求仍可能触发 IP 封禁。建议每次请求间隔 ≥3–5 秒,必要时轮换代理 IP(不推荐免费代理)。
  • 动态内容优先:Zoopla 大量依赖 React 渲染,requests 无法执行 JS,必须依赖 Selenium 或 Playwright 等驱动浏览器。
  • 替代思路参考:若仅需基础地址/邮编校验,可调用 Zoopla 官方 API(需注册开发者账号)或使用 UK 官方地理数据库(如 OS Places API)。

总结:403 错误本质是身份未被信任,而非技术不可行。通过精准模拟真实用户环境、规避自动化特征、尊重网站规则,才能在合规前提下完成可靠抓取。

https://www.php.cn/faq/2000517.html

发表回复

Your email address will not be published. Required fields are marked *