简体   繁体   中英

Scrapy: how to store url_id along with the crawled data

from scrapy import Spider, Request
from selenium import webdriver

class MySpider(Spider):
    name = "my_spider"

    def __init__(self):
        self.browser = webdriver.Chrome(executable_path='E:/chromedriver')
        self.browser.set_page_load_timeout(100)


    def closed(self,spider):
        print("spider closed")
        self.browser.close()

    def start_requests(self):
        start_urls = []
        with open("target_urls.txt", 'r', encoding='utf-8') as f:
            for line in f:
                url_id, url = line.split('\t\t')
                start_urls.append(url)

        for url in start_urls:
            yield Request(url=url, callback=self.parse)

    def parse(self, response):
        yield {
            'target_url': response.url,
            'comments': response.xpath('//div[@class="comments"]//em//text()').extract()
        }

Above is my scrapy code. I use scrapy crawl my_spider -o comments.json to run the crawler.

You may note that, for each of my url , there is an unique url_id associated with it. How can I match the each crawled result with the url_id . Ideally, I want to store the url_id in the yield output result in comments.json .

Thanks a lot!

Try to pass in meta parameter, for example. I've done some updates to your code:

def start_requests(self):
    with open("target_urls.txt", 'r', encoding='utf-8') as f:
        for line in f:
            url_id, url = line.split('\t\t')
            yield Request(url, self.parse, meta={'url_id': url_id, 'original_url': url})

def parse(self, response):
    yield {
        'target_url': response.meta['original_url'],
        'url_id': response.meta['url_id'],
        'comments': response.xpath('//div[@class="comments"]//em//text()').extract()
    }

Answering to the question and to the comment, try something like this:

from scrapy import Spider, Request
from selenium import webdriver

class MySpider(Spider):
    name = "my_spider"

    def __init__(self):
        self.browser = webdriver.Chrome(executable_path='E:/chromedriver')
        self.browser.set_page_load_timeout(100)


    def closed(self,spider):
        print("spider closed")
        self.browser.close()

    def start_requests(self):

        with open("target_urls.txt", 'r', encoding='utf-8') as f:
            for line in f:
                url_id, url = line.split('\t\t')

                yield Request(url=url, callback=self.parse, meta={'url_id':url_id,'url':url})


    def parse(self, response):
        yield {
        'target_url': response.meta['url'],
        'comments': response.xpath('//div[@class="comments"]//em//text()').extract(),
        'url_id':response.meta['url_id']
    }

As said in the previous answer, you can pass parameters between various methods, using META ( http://scrapingauthority.com/scrapy-meta ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM