Python Scrapy - Ajax 分页 Tripadvisor

标签 python ajax pagination web-scraping scrapy

我正在使用 Python-Scrapy 来删除 tripadvisor 成员(member)页面的评论。 这是我正在使用的网址:http://www.tripadvisor.com/members/scottca075

我可以使用 scrapy 获取第一页。我无法获取其他页面。单击“下一步”按钮后,我在浏览器的“网络”选项卡中观察到了 XHR 请求。

发送一个 GET 和一个 POST 请求: 在检查 GET 请求的参数时,我看到:

action : undefined_Other_ClickNext_REVIEWS_ALL
gaa : Other_ClickNext_REVIEWS_ALL
gal : 50
gams : 0
gapu : Vq85qQoQKjYAABktcRMAAAAh
gass : members`

请求网址为

 `http://www.tripadvisor.com/ActionRecord?action=undefined_Other_ClickNext_REVIEWS_ALL&gaa=Other_ClickNext_REVIEWS_ALL&gal=0&gass=members&gapu=Vq8xPAoQLnMAAUutB9gAAAAJ&gams=1`

参数gal表示偏移量。每页有 50 条评论。单击下一步按钮移至第二页时,参数 gal 设置为 50。然后,100,150,200..等等。

我想要的数据在json格式的POST请求中。 Image of JSON data in POST request 。 post 请求的请求 URL 为 http://www.tripadvisor.com/ModuleAjax?

我对如何在 scrapy 中发出请求来获取数据感到困惑。 我尝试使用 FormRequest 如下:

pagination_url = "http://www.tripadvisor.com/ActionRecord"
form_date = {'action':'undefined_Other_ClickNext_REVIEWS_ALL','gaa':'Other_ClickNext_REVIEWS_ALL', 'gal':'0','gams':'0','gapu':'Vq8EngoQL3EAAJKgcx4AAAAN','gass':'members'}
FormRequest(url=self.pagination_url, formdata=formdata, callback=self.parseItem)

我还尝试在 FormRequest 中设置 header 选项

headers = {'Host':'www.tripadvisor.com','Referer':'http://www.tripadvisor.com/members/prizm','X-Requested-With': 'XMLHttpRequest'}

如果有人可以解释我所缺少的内容并指出我正确的方向,那就太好了。我已经没有想法了。

而且,我知道我可以使用 Selenium 。但我想知道是否有更快的方法来做到这一点。

最佳答案

使用ScrapyJS - Scrapy+JavaScript 集成

要在项目中使用ScrapyJS,首先需要启用中间件:

DOWNLOADER_MIDDLEWARES = {
    'scrapyjs.SplashMiddleware': 725,
}

例如,如果我们想检索页面渲染的 HTML,我们可以这样做:

    import scrapy

    class MySpider(scrapy.Spider):
    start_urls = ["http://example.com", "http://example.com/foo"]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, self.parse, meta={
                'splash': {
                    'endpoint': 'render.html',
                    'args': {'wait': 0.5}
                }
            })

    def parse(self, response):
        # response.body is a result of render.html call; it
        # contains HTML processed by a browser.
        # …

一个常见的场景是用户需要在页面显示之前单击按钮。我们可以使用 jQuery 和 Splash 来处理这个问题:

function main(splash)
    splash:autoload("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js")
    splash:go("http://example.com")
    splash:runjs("$('#some-button').click()")
    return splash:html()
end

了解更多详情check here

关于Python Scrapy - Ajax 分页 Tripadvisor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35129508/

相关文章:

javascript - 在Jquery中解析Json数据

javascript - 在 Wordpress Admin 中从 PHP 数组创建 'Download to CSV' 按钮

php - 如何使用此分页代码获取页面上的项目数?

python - STATICFILES_DIRS 设置使我的管理小部件覆盖消失

python - 比提供的解决方案更快地获取排列索引和索引处的排列

c# - AJAX 函数调用成功

php - 自定义分类分页 Wordpress

php - 获取分页页码的公式是什么?

Python openpyxl load_workbook 错误 : TypeError (NoneType not Iterable) and ValueError (Max. 值为 180)

python - 使用sklearn线性回归,如何限制计算的回归系数大于0?