使用scrapy从xml中提取链接

2024-04-20 03:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xml页面,其结构如下:

<item>
  <pubDate>Sat, 12 Dec 2015 16:35:00 GMT</pubDate>
  <title>
   some text
  </title>
  <link>
     http://www.example.com/index.xml
  </link>
  ...

我想提取并跟踪<links>标记中的链接。在

我只有以下默认代码:

^{pr2}$

但我不知道如何跟踪“文本”标签。我实际上试过linkextractortags='links'选项,但没有用。日志有效地转到页面,得到200个回复,但没有得到任何链接。在


Tags: texthttptitle链接linksome页面xml
2条回答

这里的关键问题是,这不是一个常规的HTML输入,而是一个XML提要,链接位于元素texts中,而不是属性中。我想你只需要这里的^{}

import scrapy
from scrapy.spiders import XMLFeedSpider

class MySpider(XMLFeedSpider):
    name = 'myspider'
    start_urls = ['url_here']

    itertag = "item"

    def parse_node(self, response, node):
        for link in node.xpath(".//link/text()").extract():
            yield scrapy.Request(link.strip(), callback=self.parse_link)

    def parse_link(self, response):
        print(response.url)

你应该用xml.etree图书馆。在

import xml.etree.ElementTree as ET



res = '''
<item>
  <pubDate>Sat, 12 Dec 2015 16:35:00 GMT</pubDate>
  <title>
   some text
  </title>
  <link>
     http://www.example.com/index.xml
  </link>
</item>
'''

root = ET.fromstring(res)
results = root.findall('.//link')
for res in results:
    print res.text

输出如下:

^{pr2}$

相关问题 更多 >