使用 Scrapy 的 FormRequest.from_response 方法自动抓取下拉菜单数据

Using Scrapy's FormRequest.from_response method automate scraping of dropdown menu wise data

过去两天我一直在为这个问题苦苦挣扎。我需要从 this 网站抓取所有 "Cadres" 或类别的数据。遗憾的是,该网站允许通过下拉菜单 "Select Cadre" 访问此数据,该菜单没有 "All Categories" 选项。为了避免这种情况,我使用了 Scrapy 的 FormRequest.from_response 方法,但是蜘蛛返回的是一个没有数据的空白文件。任何帮助表示赞赏。这是代码:

import scrapy

class IASWinnerSpider(scrapy.Spider):

    name = 'iaswinner_list'
    allowed_domains = ['http://civillist.ias.nic.in']

    def start_requests(self):
        urls = [ 'http://civillist.ias.nic.in/UpdateCL/DraftCL.asp' ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        return scrapy.FormRequest.from_response(response, method='POST',
                    formdata={'cboCadre': 'UT'}, dont_click=True, callback=self.after_post)

    def after_post(self, response):

        table      = response.xpath('/html/body/div/table//tr')

        for t in table:

            yield {
                'serial': t.xpath('td[1]/text()').extract(),
                'name': t.xpath('td[2]/text()').extract(),
                'qual': t.xpath('td[3]/text()').extract(),
                'dob': t.xpath('td[4]/text()').extract(),
                'post': t.xpath('td[5]/text()').extract(),
                'rem': t.xpath('td[6]/text()').extract(),
            }

当我运行你的代码时,我在日志中看到了这个:

2017-08-19 15:52:20 [scrapy.spidermiddlewares.offsite] DEBUG: Filtered offsite request to 'civillist.ias.nic.in': <POST http://civillist.ias.nic.in/UpdateCL/DraftCL.asp>

只需将 allowed_domains 更改为:

allowed_domains = ['civillist.ias.nic.in']

而且有效。