首页 > 解决方案 > Scrapy 不能刮桌子,空空如也

问题描述

嗨,我试图从以下 URL 中的表(id:datatable-1)中抓取一些数据: https ://www.timeshighereducation.com/world-university-rankings/2021/world-ranking#!/page/0/长度/25/sort_by/scores_overall/sort_order/asc/cols/scores

我的蜘蛛中有这段代码:

import scrapy


class ScrapeTableSpider(scrapy.Spider):
    name = "scrape-table"
    allowed_domains = ['https://www.timeshighereducation.com/world-university-rankings/2021/world-ranking#!/page/0/length/25/sort_by/scores_overall/sort_order/asc/cols/scores']
    start_urls = ['https://www.timeshighereducation.com/world-university-rankings/2021/world-ranking#!/page/0/length/25/sort_by/scores_overall/sort_order/asc/cols/scores']

    def start_requests(self):
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
        for url in self.start_urls:
            yield scrapy.Request(url=url, headers=headers, callback=self.parse)

    def parse(self, response):
        from scrapy.shell import inspect_response
        inspect_response(response, self)

        table = response.xpath('//*[@id="datatable-1"]//tbody')
        rows = table.xpath('//tr')

我使用外壳,所以我可以

view(response)

如您所见,桌子是空的。关于我如何完成这项工作的任何线索?感谢所有帮助。

第一个问题,如果有问题,请见谅。

标签: pythonscrapyscreen-scraping

解决方案


当您使用view(response)它时,应该将您引导到您获取的页面。
如果该命令返回空,则意味着您的原始提取返回空。

快速浏览一下 scrapy shell,尝试获取您正在使用的 URL 会返回 403 代码。

代码 403 通常意味着您被拒绝访问该页面。

此外,该表似乎在 javascript 中。
这意味着要抓取它,您将需要一个无头浏览器。
最受欢迎的一种是Selenium


推荐阅读