【问题标题】:Scrapy crawl and follow links within hrefScrapy 抓取并关注 href 中的链接
【发布时间】:2015-04-08 01:27:12
【问题描述】:

我对scrapy非常陌生。我需要从 URL 的主页跟踪 href 到多个深度。再次在 href 链接中,我有多个 href。我需要遵循这些href,直到我到达我想要的页面来抓取。 我的页面的示例 html 是:

初始页面

<div class="page-categories">
 <a class="menu"  href="/abc.html">
 <a class="menu"  href="/def.html">
</div>

abc.html 内

<div class="cell category" >
 <div class="cell-text category">
 <p class="t">
  <a id="cat-24887" href="fgh.html"/>
</p>
</div>

我需要从这个 fgh.html 页面中抓取内容。 谁能建议我从哪里开始。我阅读了有关 Linkextractors 的信息,但找不到合适的参考资料。谢谢你

【问题讨论】:

  • 您能否分享指向您正在抓取的实际网站的链接?另外,分享您目前拥有的代码。另外,您怎么知道这是您需要关注的链接:是因为有一个以cat- 开头的id 属性吗?
  • 好吧,我正在刮codecheck.info,我正在尝试其他更简单的教程。如果您能指出一些方法而不是实际的代码,将会非常有帮助。

标签: python web-scraping scrapy scrapy-spider


【解决方案1】:

据我所知,我可以这么说:

  • 产品类别的 URL 始终以 .kat 结尾
  • 产品的网址包含 id_ 后跟一组数字

让我们使用这些信息来定义我们的蜘蛛rules

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


class CodeCheckspider(CrawlSpider):
    name = "code_check"

    allowed_domains = ["www.codecheck.info"]
    start_urls = ['http://www.codecheck.info/']

    rules = [
        Rule(LinkExtractor(allow=r'\.kat$'), follow=True),
        Rule(LinkExtractor(allow=r'/id_\d+/'), callback='parse_product'),
    ]

    def parse_product(self, response):
        title = response.xpath('//title/text()').extract()[0]
        print title

换句话说,我们要求蜘蛛跟踪每个类别链接,并在爬取包含id_ 的链接时通知我们——这对我们来说意味着我们找到了一个产品——在这种情况下,为了例如,我在控制台上打印页面标题。这应该会给你一个很好的起点。

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2015-05-02
    • 2017-05-29
    • 1970-01-01
    • 2016-01-23
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多