Python RSS Web抓取选择正确的元素

2024-04-20 11:42:01 发布

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

我发表了一篇文章来帮助我从RSS提要中获取的数据的输出格式。在

我收到的答案正是我所需要的,输出格式现在是所需的。在

更新代码如下:

import urllib2
from urllib2 import urlopen
import re
import cookielib
from cookielib import CookieJar
import time

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent','Mozilla/5.0')]

def main():
    try:
        page = 'http://feeds.link.co.uk/thelink/rss.xml'
        sourceCode = opener.open(page).read()

        try:
            titles = re.findall(r'<title>(.*?)</title>',sourceCode)
            desc = re.findall(r'<description>(.*?)</description>',sourceCode)
            links = re.findall(r'<link>(.*?)</link>',sourceCode)
            pub = re.findall(r'<pubDate>(.*?)</pubDate>',sourceCode)

            for i in range(len(titles)):
                print titles[i]
                print desc[i]
                print links[i]
                print pub[i]
                print ""

        except Exception, e:
            print str(e)

    except Exception, e:
        print str(e)

main() 

这将按我所希望的方式运行并输出到控制台,但当它完成时,我收到一个“list index out of range”错误,因为元素与count不匹配。在

我从中提取数据的xml在头中有一些使用的元素,这些元素会导致标题、描述和链接失去顺序并导致错误。在

xml如下:

^{pr2}$

有没有一种方法可以更改python代码,以确保它忽略头元素而只使用下面的公共元素?在

我已经检查了一些RSS提要,它们是以相同的方式创建的,因此我编写代码使用这段代码,并将URL更改为从几个RSS提要中提取的URL,以便在raspberry Pi控制台上使用。在

非常感谢你的帮助。在


Tags: 数据代码importre元素格式linkxml
3条回答

您应该使用正确的xml解析器,比如Beautiful Soup,而不是regex。在

from bs4 import BeautifulSoup

data = sourceCode # your sourceCode variable from your main() function

soup = BeautifulSoup(data)
for item in soup.find_all('item'):
    for tag in ['title', 'description', 'link', 'pubdate']:
        print(tag.upper(), item.find(tag).text)
    print()

输出:

^{pr2}$

好吧,我能说什么呢????在

BeautifulSoup本可以帮我省去很多打字:)

import urllib2
from bs4 import BeautifulSoup
url = "http://feeds.link.co.uk/thelink/rss.xml"
sourceCode = urllib2.urlopen(url).read()

data = sourceCode 

soup = BeautifulSoup(data)
for item in soup.find_all('item'):
    for tag in ['title', 'description', 'link', 'pubdate']:
        print(tag.upper(), item.find(tag).text)
    print()

你试过用beauthoulsoup4吗?找到你想要的元素会容易得多。在

用这样的代码:

title = soup.find('title')
if title:
    print title.text

另外,为了避免“元素超出范围错误”,可以先检查列表中是否有足够的元素:

^{pr2}$

我希望这有帮助:)

相关问题 更多 >