【问题标题】:How to use Scrapy and Splash to crawl LeetCode如何使用 Scrapy 和 Splash 爬取 LeetCode
【发布时间】:2019-05-28 10:31:19
【问题描述】:

我是 Python 和 Spider 的新手。我现在正在尝试使用Scrapy和Splash来爬取用js渲染的动态页面,比如从https://leetcode.com/problemset/all/爬取问题。

但是当我在 https://leetcode.com/problems/two-sum/ 中使用 response.xpath("//div[@class='css-1ponsav']") 时,似乎没有得到任何信息。 同样,在登录界面https://leetcode.com/accounts/login/中,当你尝试调用SplashFormRequest.from_response(response,...)登录时,会返回ValueError: No element found in 。

我对前端了解不多。我不知道 LeetCode 使用的 graphQL 是否有任何关系。还是其他原因?

这里是代码。

# -*- coding: utf-8 -*-
import json
import scrapy
from scrapy import Request, Selector
from scrapy_splash import SplashRequest
from leetcode_problems.items import ProblemItem


class TestSpiderSpider(scrapy.Spider):
    name = 'test_spider'
    allowed_domains = ['leetcode.com']

    single_problem_url = "https://leetcode.com/problems/two-sum/"

    def start_requests(self):
        url = self.single_problem_url
        yield SplashRequest(url=url, callback=self.single_problem_parse, args={'wait': 2})

    def single_problem_parse(self, response):
        submission_page = response.xpath("//div[@data-key='submissions']/a/@href").extract_first()
        submission_text = response.xpath("//div[@data-key='submissions']//span[@class='title__qRnJ']").extract_first()
        print("submission_text:", end=' ')
        print(submission_text) #Print Nothing
        if submission_page:
            yield SplashRequest("https://leetcode.com" + submission_page, self.empty_parse, args={'wait': 2})

【问题讨论】:

    标签: python scrapy splash-screen


    【解决方案1】:

    我对 Splash 不太熟悉,但 98% 的 Javascript 生成的网站可以通过查看 Network 选项卡下的 XHR 过滤器来查找生成这些输出的 POST 或 GET 响应。

    在您的情况下,我可以看到有一个响应可以生成整个页面,而不需要任何特殊的查询参数或 API 密钥。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多