python - 如何在带有文本站点地图的站点上使用Scrapy站点地图蜘蛛?

标签 python scrapy sitemap

我尝试使用通用的 Scrapy.spider 来跟踪链接,但它不起作用 - 因此我想到了通过访问 sitemap.txt 来简化流程的想法,但这并没有也不起作用!

我编写了一个简单的示例(以帮助我理解算法),让蜘蛛遵循我网站上指定的站点地图:https://legion-216909.appspot.com/sitemap.txt它的目的是导航站点地图上指定的 URL,将其打印到屏幕上并将结果输出到 links.txt 文件中。代码:

import scrapy
from scrapy.spiders import SitemapSpider

class MySpider(SitemapSpider):
    name = "spyder_PAGE"
    sitemap_urls = ['https://legion-216909.appspot.com/sitemap.txt']

    def parse(self, response):
        print(response.url)
        return response.url

我将上面的蜘蛛运行为 Scrapycrawlspyder_PAGE > links.txt 但返回了一个空文本文件。我已经多次浏览了 Scrapy 文档,但还是缺少一些东西。我哪里出错了?

最佳答案

SitemapSpider需要 XML 站点地图格式,导致蜘蛛退出并出现以下错误:

[scrapy.spiders.sitemap] WARNING: Ignoring invalid sitemap: <200 https://legion-216909.appspot.com/sitemap.txt>

自从您的 sitemap.txt file 只是一个简单的列表或 URL,用字符串方法分割它们会更容易。

例如:

from scrapy import Spider, Request

class MySpider(Spider):
    name = "spyder_PAGE"
    start_urls = ['https://legion-216909.appspot.com/sitemap.txt']

    def parse(self, response):
        links = response.text.split('\n')
        for link in links:
            # yield a request to get this link
            print(link)

# https://legion-216909.appspot.com/index.html
# https://legion-216909.appspot.com/content.htm
# https://legion-216909.appspot.com/Dataset/module_4_literature/Unit_1/.DS_Store

关于python - 如何在带有文本站点地图的站点上使用Scrapy站点地图蜘蛛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52486744/

相关文章:

asp.net-mvc - Asp.net Mvc : List all the actions on a controller with specific attribute

Python写递归函数

python - 如何检查两个 POS 标签在 NLTK 中属于同一类别?

python - Scrapy Spider解析器调用函数

python - 如何使用scrapy从主脚本中获取抓取的项目?

asp.net-mvc - MVCSiteMapProvider 面包屑不正确的父节点 ID

php - 从 Magento sitemap.xml 生成中排除某些产品

Python正则表达式跨多行findall

python - 使用 SPARQLWrapper 插入/删除/更新查询

Python Scrapy 函数调用