Scrape using multiple POST data from the same URL

对着背影说爱祢 提交于 2019-12-04 11:45:34

Assuming you have a phones.csv file with phones in it:

01253873647
01253776535
01142726749

Here's your spider:

import csv
from scrapy.item import Item, Field

from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.selector import HtmlXPathSelector


class BtwItem(Item):
    fttcAvailable = Field()
    phoneNumber = Field()


class BtwSpider(BaseSpider):
    name = "btw"
    allowed_domains = ["samknows.com"]

    def start_requests(self):
        yield Request("http://www.samknows.com/broadband/broadband_checker", self.parse_main_page)

    def parse_main_page(self, response):
        with open('phones.csv', 'r') as f:
            reader = csv.reader(f)
            for row in reader:
                phone_number = row[0]
                yield FormRequest.from_response(response,
                                                formdata={'broadband_checker[phone]': phone_number},
                                                callback=self.after_post,
                                                meta={'phone_number': phone_number})

    def after_post(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//div[@id="results"]')

        phone_number = response.meta['phone_number']
        for site in sites:
            item = BtwItem()

            fttc = site.select("div[@class='content']/div[@id='btfttc']/ul/li/text()").extract()
            item['phoneNumber'] = phone_number
            item['fttcAvailable'] = 'not' in fttc[0]

            yield item

Here's what was scraped after running it:

{'fttcAvailable': False, 'phoneNumber': '01253873647'}
{'fttcAvailable': False, 'phoneNumber': '01253776535'}
{'fttcAvailable': True, 'phoneNumber': '01142726749'}

The idea is to scrape the main page using start_requests, then read the csv file line-by-line in the callback and yield new Requests for each phone number (csv row). Additionally, pass phone_number to the callback through the meta dictionary in order to write it to the Item field (I think you need this to distinguish items/results).

Hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!