Scrapy - 关注RSS链接

时间:2010-05-30 14:40:51

标签: python web-crawler scrapy

我想知道是否有人试图使用提取/关注RSS项链接 SgmlLinkExtractor / CrawlSpider。我无法让它发挥作用......

我使用以下规则:


   rules = (
       Rule(SgmlLinkExtractor(tags=('link',), attrs=False),
           follow=True,
           callback='parse_article'),
       )

(请记住,rss链接位于 link 标记中)。

我不知道如何告诉SgmlLinkExtractor提取text() 链接,而不是搜索属性......

欢迎任何帮助, 提前致谢

4 个答案:

答案 0 :(得分:7)

CrawlSpider规则无法正常工作。您可能需要子类化BaseSpider并在您的蜘蛛回调中实现自己的链接提取。例如:

from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import XmlXPathSelector

class MySpider(BaseSpider):
    name = 'myspider'

    def parse(self, response):
        xxs = XmlXPathSelector(response)
        links = xxs.select("//link/text()").extract()
        return [Request(x, callback=self.parse_link) for x in links]

你也可以通过运行例如:

来尝试shell中的XPath
scrapy shell http://blog.scrapy.org/rss.xml

然后输入shell:

>>> xxs.select("//link/text()").extract()
[u'http://blog.scrapy.org',
 u'http://blog.scrapy.org/new-bugfix-release-0101',
 u'http://blog.scrapy.org/new-scrapy-blog-and-scrapy-010-release']

答案 1 :(得分:6)

现在可以使用XMLFeedSpider

答案 2 :(得分:0)

我使用CrawlSpider完成了它:

class MySpider(CrawlSpider):
   domain_name = "xml.example.com"

   def parse(self, response):
       xxs = XmlXPathSelector(response)
       items = xxs.select('//channel/item')
       for i in items: 
           urli = i.select('link/text()').extract()
           request = Request(url=urli[0], callback=self.parse1)
           yield request

   def parse1(self, response):
       hxs = HtmlXPathSelector(response)
       # ...
       yield(MyItem())

但我不确定这是一个非常合适的解决方案......

答案 3 :(得分:-2)

XML示例来自scrapy doc XMLFeedSpider

from scrapy.spiders import XMLFeedSpider
from myproject.items import TestItem

class MySpider(XMLFeedSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com/feed.xml']
    iterator = 'iternodes'  # This is actually unnecessary, since it's the default value
    itertag = 'item'

    def parse_node(self, response, node):
        self.logger.info('Hi, this is a <%s> node!: %s', self.itertag, ''.join(node.extract()))

        #item = TestItem() 
        item = {} # change to dict for removing the class not found error
        item['id'] = node.xpath('@id').extract()
        item['name'] = node.xpath('name').extract()
        item['description'] = node.xpath('description').extract()
        return item