【问题标题】:Scraping all urls in a website using scrapy not retreiving complete urls associated with that domain使用scrapy抓取网站中的所有网址,而不是检索与该域关联的完整网址
【发布时间】:2022-01-15 08:44:57
【问题描述】:

我正在尝试抓取 https://www.laphil.com/ https://madisonsymphony.org/ https://www.californiasymphony.org/ 等网站中的所有网址,仅举几例。我正在抓取许多网址,但没有获得与该域相关的完整网址。我不知道为什么它没有抓取所有的网址。

代码

items.py

import scrapy

class ScraperItem(scrapy.Item):
    # The source URL
    url_from = scrapy.Field()
    # The destination URL
    url_to = scrapy.Field()

my_crawler.py

import re
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from w3lib.url import url_query_cleaner

def process_links(links):
    for link in links:
        link.url = url_query_cleaner(link.url)
        yield link

class myCrawler(CrawlSpider):
    name = 'symphony'
    allowed_domains = ['laphil.com']
    start_urls = ['https://www.laphil.com/']
    rules = (
        Rule(
            LinkExtractor(
                deny=[
                ],
            ),
            process_links=process_links,
            callback='parse_item',
            follow=True
        ),
    )

    def parse_item(self, response):
        yield {
            'url': response.url
        }
        next_page = response.css('a::attr(href)').extract()
        yield {"sub_url":[response.urljoin(ind_url) for ind_url in next_page]}}

执行

scrapy crawl symphony --logfile laph.log -o laph.jl -t jsonlines

如果我们去一个从爬取的url列表中获取的url,例如https://www.laphil.com/events/series/210,那么有几个链接从这个页面直接指向了https://www.laphil.com/events/performances/1356/2022-01-08/prokofiev-and-mtt,https://www.laphil.com/events/performances/1337/2021-11-06/reich-adams-and-rachmaninoff等没有获取到。如何在结果列表中潦草地写下所有这些 url 并避免重复的 url

【问题讨论】:

  • 我正在从页面获取所有网址。您想在哪里删除重复项?是在yield {"sub_url":next_page} 行吗?
  • @SuperUser 感谢您的友好回复。我正在寻找一种 csv 格式,该格式可以转换为 pandas 数据帧以进行处理,其中包含一个列,该列中没有重复的 url。我试图在 CLI 中保存,但使用 pandas 模块读取存在问题。还有很多重复的网址。

标签: python scrapy web-crawler


【解决方案1】:

蜘蛛.py:

import re
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from w3lib.url import url_query_cleaner


def process_links(links):
    for link in links:
        link.url = url_query_cleaner(link.url)
        yield link


class myCrawler(CrawlSpider):
    name = 'symphony'
    allowed_domains = ['laphil.com']
    start_urls = ['https://www.laphil.com']
    base_url = 'https://www.laphil.com'

    custom_settings = {
        # in order to reduce the risk of getting blocked
        'DOWNLOADER_MIDDLEWARES': {'tempbuffer.middlewares.RotateUserAgentMiddleware': 400, },
        'COOKIES_ENABLED': False,
        'CONCURRENT_REQUESTS': 6,
        'DOWNLOAD_DELAY': 2,

        # This settings are a must:
        
        # Duplicates pipeline
        'ITEM_PIPELINES': {'tempbuffer.pipelines.DuplicatesPipeline': 300},

        # In order to create a CSV file:
        'FEEDS': {'csv_file.csv': {'format': 'csv'}}
    }

    rules = (
        Rule(
            LinkExtractor(allow_domains='laphil.com'),
            process_links=process_links,
            callback='parse_item',
            follow=True
        ),
    )

    def parse_item(self, response):
        yield {
            'url': response.url
        }

        # see if you really need this loop (since you're parsing all the urls in the domain anyway, and you'll need
        # to filter all those duplicates):

        all_urls = response.css('a::attr(href)').getall()

        # In order to change from relative to absolute url in the pipeline:
        self.base_url = response.url

        for url in all_urls:
            yield {
                'url': url
            }

管道.py:

from scrapy.exceptions import DropItem


class DuplicatesPipeline:
    def __init__(self):
        self.scraped_urls = set()

    def process_item(self, item, spider):
        url = item['url'].strip()

        # if it's a relative url then convert to absolute url
        if 'http' not in url:
            url = spider.base_url + url
            item['url'] = url

        if url in self.scraped_urls:
            raise DropItem(f'Duplicate url: \"{url}\"')
        else:
            self.scraped_urls.add(url)
            return item
  1. 我没有添加 middlewares.py 文件,因为它不是必需的,而且它有很多行。
  2. 在您的代码中,而不是 tempbuffer 应该是 your project's name(您需要在管道的 custom_settings 中替换它)。
  3. 我将域作为唯一允许的域添加到规则中,这样您就不会抓取任何不想要的内容。
  4. 我验证了重复管道工作正常,并且它实际上创建了一个包含一列的 csv 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2018-09-23
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多