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()
}