gpt4 book ai didi

python - Beautiful Soup 在 """和 "<"等特殊字符上崩溃

转载 作者:行者123 更新时间:2023-11-30 23:32:46 25 4
gpt4 key购买 nike

我正在尝试使用 beautiful soup 来抓取基于原子的 RSS feed,但事实证明这很困难。捕获数据一切顺利,直到 <item>出现破坏代码并使脚本崩溃的情况。这样<item>始终具有标签(Firefox 将其标记为橙色),例如“<”或“& 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

最佳答案

不确定您在谈论哪个问题,但我在运行代码时遇到此错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' in position 54: ordinal not in range(128)

为了解决这个问题,我刚刚添加了编码:

for thing in news_stuff:
print '<a href="'
print thing[1]
print '"target="_blank">'
print thing[0].encode("utf-8")
print '</a><br/>'
i += 1

脚本执行后没有任何错误。

关于python - Beautiful Soup 在 "&quot;"和 "&lt;"等特殊字符上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19229389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com