python - 使用 Scrapy 从文本文件中的多个 URL 中抓取所有外部链接

标签 python url web-scraping scrapy web-crawler

我是 Scrapy 和 Python 的新手,因此我是一个初学者。我希望能够让 Scrapy 读取包含大约 100k url 种子列表的文本文件,让 Scrapy 访问每个 URL,并提取在每个种子 URL 上找到的所有外部 URL(其他站点的 URL)并将结果导出到一个单独的文本文件。

Scrapy 应该只访问文本文件中的 URL,而不是抓取并跟踪任何其他 URL。

我希望能够让 Scrapy 尽快工作,我有一个非常强大的服务器,有 1GBS 线路。我列表中的每个 URL 都来自一个唯一的域,因此我根本不会对任何 1 个站点进行重击,因此不会遇到 IP 阻止。

我如何在 Scrapy 中创建一个项目,以便能够从存储在文本文件中的 URL 列表中提取所有外部链接?

谢谢。

最佳答案

您应该使用:
1. start_requests 函数用于读取 url 列表。
2. 所有“a”html 元素的 css 或 xpath 选择器。

from scrapy import Spider

class YourSpider(Spider):
    name = "your_spider"

    def start_requests(self):
        with open('your_input.txt', 'r') as f:  # read the list of urls
           for url in f.readlines()             # process each of them
               yield Request(url, callback=self.parse)

    def parse(self, response):
        item = YourItem(parent_url=response.url)
        item['child_urls'] = response.css('a::attr(href)').extract()
        return item

有关 start_requests 的更多信息:
http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.start_requests

要将抓取的项目提取到另一个文件,请使用项目管道或源导出。基本管道示例如下:
http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-a-json-file

关于python - 使用 Scrapy 从文本文件中的多个 URL 中抓取所有外部链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39192171/

相关文章:

python - 最短的计数方式?

python - Django Rest Framework 反转 URL

python - django 将枚举中的项目翻译成其他语言

python - 如何使用 Web URL 调用/运行 Python 脚本?

url - Spring Security获取intercept-url中模式的访问属性

python - 如何使用 beautiful soup 从 shopee 抓取数据

python - Python Dataframe 子集的平均值

php - 尝试使用 php 获取子域 URL

python - 尽管 id 存在,Python 中的 Beautiful Soup 找不到 id

r - 有没有办法在原始数据中添加文本(链接)?