【发布时间】:2018-07-15 07:53:15
【问题描述】:
我有两个scrapy,第一个抓取站点地图并提取网址并将其放入txt文件中,第二个读取并逐行抓取此网址。
我的代码如下:
class sitemapSpider(SitemapSpider):
name = "filmnetmapSpider"
sitemap_urls = ['http://filmnet.ir/sitemap.xml']
sitemap_rules = [
('/series/', 'parse_item')
]
storage_file = 'urls.txt'
def parse_item(self, response):
videoid = response.url
with open(self.storage_file, 'a') as handle:
yield handle.writelines(videoid + '\n')
第二只蜘蛛:
class filmnetSpider(scrapy.Spider):
name = 'filmnetSpider'
def start_requests(self):
with open('urls.txt') as fp:
for line in fp:
yield Request(line.strip(), callback=self.parse_website)
def parse_website(self, response):
hxs = HtmlXPathSelector(response)
url = hxs.xpath('//script[@type="application/ld+json"]/text()').extract()
url = ast.literal_eval(json.dumps(url))
url = url[1]
obj = json.loads(url)
poster = obj['image']
name = obj['name']
description = obj['description']
如何更改代码以删除对文件的读/写?
如何在其中使用回调?
注意:此代码不适用于一个scrapy spider;代码为:两个给定的scrapy + 波纹管代码,如doc中所说的示例
process = CrawlerProcess()
process.crawl(filmnetSpider)
process.crawl(sitemapSpider)
process.start()
【问题讨论】:
-
你能把你在一只scrapy spider上试过的代码贴出来吗?
-
感谢您的关注,问题已修改。
-
这段代码不会在文本文件中写入任何内容,它只是从站点地图中提取网址。
-
你说要删除对文件的读/写...所以代码不再使用文件并将url直接传递给回调...
-
我有一个问题;那么你为什么在你的代码中使用'storage_file'呢?此代码是否会抓取 url 并提取请求的项目(如“图像”或“名称”)?
标签: python callback scrapy scrapy-spider