繁体   English   中英

如何获取 Python Scrapy 以从 web 页面中提取所有外部链接的所有域?

[英]How to I get Python Scrapy to extract all of the domains of all external links from a web page?

我希望循环检查每个链接 - 如果它转到 output 它的外部域 - 目前它输出所有链接(内部和外部)。 我搞砸了什么? (为了测试,我已将代码调整为仅从单个页面运行,而不是爬取站点的 rest。)

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
import re

class MySpider(CrawlSpider):
    name = 'crawlspider'
    allowed_domains = ['en.wikipedia.org']
    start_urls = ['https://en.wikipedia.org/wiki/BBC_News']

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=False),
    )

    def parse_item(self, response):
        item = dict()
        item['url'] = response.url
        item['title']=response.xpath('//title').extract_first()
        for link in LinkExtractor(allow=(),deny=self.allowed_domains).extract_links(response):
            item['links']=response.xpath('//a/@href').extract()
        return item

您的parse_item方法中的逻辑看起来不太正确

def parse_item(self, response):
    item = dict()
    item['url'] = response.url
    item['title']=response.xpath('//title').extract_first()
    for link in LinkExtractor(allow=(),deny=self.allowed_domains).extract_links(response):
        item['links']=response.xpath('//a/@href').extract()
    return item

您正在遍历提取器中的每个link ,但始终将item["links"]设置为完全相同的内容(来自响应页面的所有链接)。 我希望您尝试将item["links"]设置为来自LinkExtractor的所有链接? 如果是这样,您应该将方法更改为

def parse_item(self, response):
    item = dict()
    item['url'] = response.url
    item['title'] = response.xpath('//title').extract_first()
    links = [link.url for link in LinkExtractor(deny=self.allowed_domains).extract_links(response)]        
    item['links'] = links
    return item

如果您真的只想要域,那么您可以使用urlparse中的urllib.parse来获取netloc 您可能还想使用set删除重复项。 所以你的解析方法会变成(最好在文件顶部导入)

def parse_item(self, response):
    from urllib.parse import urlparse
    item = dict()
    item["url"] = response.url
    item["title"] = response.xpath("//title").extract_first()
    item["links"] = {
        urlparse(link.url).netloc
        for link in LinkExtractor(deny=self.allowed_domains).extract_links(response)
    }   
    return item

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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