You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Scrapy-Splash抓取JS网站无结果,求问题排查方案

解决Scrapy-Splash爬取JS渲染页面无结果的问题

1. 确认Splash服务正常运行

先确保本地http://localhost:8050的Splash服务已启动,用Docker启动的命令如下:

docker run -p 8050:8050 scrapinghub/splash

服务未启动会导致请求无法正确渲染页面。

2. 给SplashRequest添加渲染等待时间

默认SplashRequest可能在JS未完全渲染时就返回响应,导致目标元素未生成。通过wait参数设置等待时长,让页面加载完成:

def start_requests(self):
    url='https://www.askgamblers.com/online-casinos/countries/uk'
    yield SplashRequest(
        url,
        wait=3,  # 等待3秒让JS渲染完成
        callback=self.parse
    )

3. 自定义请求头(User-Agent)

部分网站会识别Splash默认的UA为爬虫,需设置真实浏览器UA:

def start_requests(self):
    url='https://www.askgamblers.com/online-casinos/countries/uk'
    yield SplashRequest(
        url,
        wait=3,
        headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
        },
        callback=self.parse
    )

4. 验证并修正XPath选择器

页面渲染后的元素结构可能和预期不符,可通过Splash预览页面确认:

  • 访问http://localhost:8050/render.html?url=https://www.askgamblers.com/online-casinos/countries/uk&wait=3,查看渲染后的源码,核对目标元素的class和路径。
  • 若目标元素class实际为card__description,修正XPath:
books = response.xpath("//div[@class='card__description']//a[starts-with(@href, '/online')]/@href").extract()

同时简化XPath,将//@href改为/@href,避免提取多余属性。

5. 启用调试模式验证渲染结果

通过args参数让Splash返回渲染后的HTML,在parse函数中打印响应内容排查问题:

def start_requests(self):
    url='https://www.askgamblers.com/online-casinos/countries/uk'
    yield SplashRequest(
        url,
        wait=3,
        headers={'User-Agent': '你的UA'},
        args={'html': 1},
        callback=self.parse
    )

def parse(self, response):
    # 打印响应前1000字符,确认页面是否渲染正确
    print(response.text[:1000])
    books = response.xpath("//div[@class='card__desc']//a[starts-with(@href, '/online')]/@href").extract()
    print(f"提取到的链接数量:{len(books)}")
    for book in books:
        url = response.urljoin(book)
        yield {'url': url}

内容的提问来源于stack exchange,提问作者Amen Aziz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:56:01