如何使用scrapy跟踪特定链接并抓取内容?

2 投票
1 回答
1974 浏览
提问于 2025-04-18 02:04

假设我有一个主页面,叫做 index.html,还有四个子页面,分别是 1.html4.html。所有页面在主页面上都是以相同的方式链接的。

我想用 Python 的 scrapy 来跟踪这些特定的链接,并按照重复的模式抓取内容。

这是我的设置:

index.html

<body>
<div class="one"><p>Text</p><a href="1.html">Link 1</a></div>
…
<div class="one"><p>Text</p><a href="4.html">Link 4</a></div>
</body>

1.html…4.html

<body>
<div class="one"><p>Text to be scraped</p></div>
</body>

我该如何在 scrapy 中设置一个 spider,只跟踪从 index.html 提取的链接呢?

我觉得教程中的例子对我帮助不大:

from scrapy.spider import Spider

class IndexSpider(Spider):
    name = "index"
    allowed_domains = ["???"]
    start_urls = [
        "index.html"
    ]

注意:这是一个简化的例子。在原始例子中,所有的 URL 都来自网络,而 index.html 包含的链接比 1…4.html 多得多。

问题是如何跟踪这些确切的链接,这些链接可以作为一个列表提供,但最终会来自一个 xpath 选择器——选择表格的最后一列,但只选择每隔一行的内容。

1 个回答

2

使用 CrawlSpider,并为 SmglLinkExtractor 指定规则:

from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

class MySpider(CrawlSpider):
    name = "mydomain"
    allowed_domains = ["www.mydomain"]
    start_urls = ["http://www.mydomain/index.html",]

    rules = (Rule(SgmlLinkExtractor(allow=('\d+.html$', ),), callback="parse_items", follow=True), )

    def parse_items(self, response):
        hxs = HtmlXPathSelector(response)
        # get the data

撰写回答