【发布时间】:2013-10-07 16:00:00
【问题描述】:
我正在尝试使用漂亮的汤来抓取基于原子的 RSS 提要,但事实证明这很困难。捕获数据一直很好,直到出现<item> 破坏代码并使脚本崩溃。这样的<item>s 始终有标签(Firefox 将它们标记为橙色),如“& lt;”或“& quot;”,而没有它们的 s 可以正常工作。我已经尝试了很多东西,比如 BeautifulStoneSoup,用正则表达式去除特殊字符,并设置“xml”参数,但没有任何效果,而且它们通常只是发出关于在 BS4 中被弃用的警告。
为什么会出现这些字符,我该如何有效地处理它们?
这是我要抓取的页面: http://www.thestar.com/feeds.articles.news.gta.rss
这是我的代码:
news_url = "http://www.thestar.com/feeds.articles.news.gta.rss" # Toronto Star RSS Feed
try:
news_rss = urllib2.urlopen(news_url)
news = news_rss.read()
news_rss.close()
soup = BeautifulSoup(news)
except:
return "error"
titles = soup.findAll('title')
links = soup.findAll('link')
for link in links:
link = link.contents # I want the url without the <link> tags
news_stuff = []
for item in titles:
if item.text == "TORONTO STAR | NEWS | GTA": # These have <title> tags and I don't want them; just skip 'em.
pass
else:
news_stuff.append((item.text, links[i])) # Here's a news story. Grab it.
i = 0
for thing in news_stuff:
print '<a href="'
print thing[1]
print '"target="_blank">'
print thing[0]
print '</a><br/>'
i += 1
【问题讨论】:
标签: python web-scraping beautifulsoup