Python 使用Scrapy抓取数据以加载更多数据?

Python 使用Scrapy抓取数据以加载更多数据?,python,post,scrapy,Python,Post,Scrapy,我需要从这个网站抓取一些新闻:。这里是新闻分类id 但如果不触发ajax加载更多内容,我只能获得第一页: 很奇怪,不同新闻类别的请求url是相同的 页面信息由referer通过标题传递。页面由表单数据发送 以下是我的代码片段: self.page += 1 url = "https://www.huxiu.com/channel/ajaxGetMore" method = "POST" headers = { "Host": "www.hux

我需要从这个网站抓取一些新闻:。这里是新闻分类id

但如果不触发ajax加载更多内容,我只能获得第一页:
很奇怪,不同新闻类别的请求url是相同的

页面信息由referer通过标题传递。页面由表单数据发送

以下是我的代码片段:

    self.page += 1
    url = "https://www.huxiu.com/channel/ajaxGetMore"
    method = "POST"

    headers = {
        "Host": "www.huxiu.com",
        "Origin": "https://www.huxiu.com",
        "Referer": "https://www.huxiu.com/channel/106.html",
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/"
            "537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Sa"
            "fari/537.36"
        ),
        "X-Requested-With": "XMLHttpRequest",
    }

    formdata = {
        "huxiu_hash_code": "9aee58d3507ecafed74df13e156ab01b",
        "page": str(self.page),
        "catId": "106"
    }

    yield FormRequest(
        url=url,
        method=method,
        headers=headers,
        formdata=formdata,
        callback=self.parse
    )

无法加载更多新闻源。如何发送post请求以获取更多新闻?

在本例中,GET和post请求似乎可以互换。 这是一种非常常见的AJAX分页技术:

如果您尝试:在浏览器中,您会看到一些包含所有分页数据的json数据以及一些元数据,如
total\u page
。这个信息很容易抓取,并且允许您同时抓取每个页面,因为您从第一个请求就知道页面计数

例如,请参见此spider for python3如何处理此类分页:

from scrapy import Spider, Request
from w3lib.url import add_or_replace_parameter

class MySpider(Spider):
    start_urls = ['https://www.huxiu.com/channel/ajaxGetMore?catId=103&page=1']

    def parse(self, response):
        data = json.loads(response.body_as_unicode())
        yield from parse_data(response)  # parse first page as well
        # yield async requests for every other page.
        for page in range(2, data['data']['total_page']):
            # make next page url by replacing page parameter
            url = add_or_replace_parameter(response.url, 'page', page)
            yield Request(url, callback=self.parse_data)

    def parse_data(self, response):
        data = json.loads(response.body_as_unicode())
        # parse json data

如果检查浏览器发送的内容,哈希代码是否始终相同?可能是哈希代码取自页面本身吗?哈希代码总是一样的。