如何找到网站的确切RSS XML路径?
我怎么才能找到一个网站的确切的 feed.xml/rss.xml/atom.xml 路径呢?
比如说,我给了一个链接 "http://www.example.com/news/today/this_is_a_news",但是它的 RSS 却指向了 "http://www.example.com/rss/feed.xml"。现在很多现代浏览器都有这个功能,我很好奇它们是怎么做到的。
你能给我举个用 Ruby、Python 或者 Bash 的代码例子吗?
3 个回答
0
在Python中,可以使用这个经典的解决方案:http://www.aaronsw.com/2002/feedfinder/
1
你也可以使用一个命令行工具,比如 xmlstarlet(可以和 HTML tidy 一起使用):
# version 1
curl -s http://stackoverflow.com/questions/2441954/how-to-find-out-the-exact-rss-xml-path-of-a-website |
tidy -q -c -wrap 0 -numeric -asxml -utf8 --merge-divs yes --merge-spans yes 2>/dev/null |
xmlstarlet sel -T -t -m "//*[local-name()='link']" --if "@type='application/atom+xml' or @type='application/rss+xml'" -m "@href" -v '.' -n
# version 2
curl -s http://stackoverflow.com/questions/2441954/how-to-find-out-the-exact-rss-xml-path-of-a-website |
tidy -q -c -wrap 0 -numeric -asxml -utf8 --merge-divs yes --merge-spans yes 2>/dev/null |
xmlstarlet sel -N x="http://www.w3.org/1999/xhtml" -T -t -m "//x:link[@type='application/atom+xml' or @type='application/rss+xml']" -v "@href" -n
2
在Ruby中,可以像这样来实现...
require 'rubygems' require 'nokogiri' require 'open-uri' html = Nokogiri::HTML(open('http://stackoverflow.com/questions/2441954/how-to-find-out-the-exact-rss-xml-path-of-a-website')) puts html.css('link[type="application/atom+xml"]').first.attr('href') # => "/feeds/question/2441954"
注意,这里使用的是绝对网址路径,这样是合法的,所以你需要在前面加上主机信息。
另外,“application/atom+xml”也可以是“application/rss+xml”或者“application/rdf+xml”,而且一个页面里可能会有多个链接,所以你需要决定怎么处理这些多个链接。根据自动发现的文档,首先出现的链接应该是优先选择的,但根据我的经验,情况并不总是这样。此外,文档中提到这些链接不应该是不同的数据类型(比如RSS和ATOM指向同一内容),而应该是不同的内容,但我也见过这种情况。