在使用Scrapy进行爬网之前,请检查文件中是否存在URL

问题描述 投票:1回答:1

我想使用Scrapy来抓取网站的数据。每个页面内容中都有一个元素,即URL。

由于网站页面太多,我只想抓取包含TXT文件中指定的URL的页面。

因此,爬虫检查网站,提取响应元素,检查该文件中是否存在从页面内容中提取的URL,将响应数据保存到JSON文件中。

这是我到目前为止:

import scrapy
import json
import uuid
import os
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class ItemSpider(CrawlSpider):
    name = "items"
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com/template/template1.html']
    rules = (Rule(LxmlLinkExtractor(allow = (), canonicalize=True, unique=True), callback = 'parse_obj', follow = True), )
    def parse_obj(self, response):
        for link in LxmlLinkExtractor(allow = self.allowed_domains, canonicalize=True, unique=True).extract_links(response):
            with open("urls.txt", "r") as checkfile:
                if response.xpath("//a[contains(text(),'example2.net')]/text()").extract() in checkfile.readlines():
                    response_obj = {}
                    counter = 1
                    for item in response.css("#dle-content"):
                        title = item.css(".storytitle::text").extract()
                        title_name = title[0]
                        response_obj[counter] = {
                        'demo': item.xpath("//a[contains(text(),'example2.net')]/text()").extract(),
                        'websiteurl': response.url,
                        'date': item.css(".copy > a:first-child::text").extract(),
                        }
                    counter += 1
                    filename = str(uuid.uuid4()) + ".json"
                    with open(os.path.join('C:/scrapy/tutorial/result/', filename), 'w') as fp:
                        json.dump(response_obj, fp)

第二个问题: 似乎爬虫不会停止爬行。该网站没有那个爬虫保存为结果的页面。它根本没有停止,生成超过150K的结果文件然后我自己停止了命令。

我认为这是重新获得的结果。我对吗?我知道scrapy不会抓取已经爬过的网址。但我认为这里可能存在一些错误,这可能会阻止这种情况发生。

python scrapy
1个回答
0
投票

您是否考虑过将要抓取的URL存储在数据库中并将其作为起始URL传递?

© www.soinside.com 2019 - 2024. All rights reserved.