首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么美丽的汤忽略了CDATA

为什么美丽的汤忽略了CDATA
EN

Stack Overflow用户
提问于 2014-10-26 21:43:24
回答 2查看 856关注 0票数 0

我正在为雅虎天气API (python2.7)使用Beautiful:

代码语言:javascript
复制
url = 'http://weather.yahooapis.com/forecastrss?w=2344116'
page=urllib2.urlopen(url).read()
soup = BeautifulSoup(page)

但在此之后,在解析的url中,没有任何CDATA。为什么美汤忽视了这一点?如何防止忽略CDATA?

在xml中:

代码语言:javascript
复制
<img src="http://l.yimg.com/a/i/us/we/52/11.gif"/>

在已分析的页面中:

正如你所看到的,CDATA已经丢失了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-26 21:51:19

CDATA部分不会被忽略;它只是按照CDATA部分应该被视为文本的方式来处理。

代码语言:javascript
复制
>>> print soup.select('description:nth-of-type(2)')[0].text

<img src="http://l.yimg.com/a/i/us/we/52/11.gif"/><br />
<b>Current Conditions:</b><br />
Light Rain Shower, 59 F<BR />
<BR /><b>Forecast:</b><BR />
Sun - Rain/Wind. High: 63 Low: 57<br />
Mon - Rain/Wind. High: 60 Low: 53<br />
Tue - PM Showers. High: 58 Low: 55<br />
Wed - Mostly Cloudy. High: 64 Low: 57<br />
Thu - Rain. High: 63 Low: 55<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Istanbul__TR/*http://weather.yahoo.com/forecast/TUXX0014_f.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>

您可以将该部分解析为一个单独的页面:

代码语言:javascript
复制
>>> description_soup = BeautifulSoup(soup.select('description:nth-of-type(2)')[0].text)
>>> description_soup.img
<img src="http://l.yimg.com/a/i/us/we/52/11.gif"/>

请注意,由于这是您正在解析的XML,请考虑使用XML模式(需要安装lxml ):

代码语言:javascript
复制
soup = BeautifulSoup(page, 'xml')

或者(更好的),使用feedparser来解析RSS提要。

票数 2
EN

Stack Overflow用户

发布于 2014-10-26 22:02:21

你为什么这么想要这些CDATA?从我所看到的情况来看,同样的数据是以一种更结构化的方式向下排列的:

代码语言:javascript
复制
In [28]: soup.findAll('yweather:forecast')
Out[28]: 
[<yweather:forecast day="Sun" date="26 Oct 2014" low="57" high="63" text="Rain/Wind" code="12">
 </yweather:forecast>,
 <yweather:forecast day="Mon" date="27 Oct 2014" low="54" high="61" text="Rain/Wind" code="12">
 </yweather:forecast>,
 <yweather:forecast day="Tue" date="28 Oct 2014" low="56" high="59" text="Rain" code="12">
 </yweather:forecast>,
 <yweather:forecast day="Wed" date="29 Oct 2014" low="57" high="63" text="AM Showers" code="39">
 </yweather:forecast>,
 <yweather:forecast day="Thu" date="30 Oct 2014" low="55" high="62" text="Light Rain" code="11">
 <guid ispermalink="false">TUXX0014_2014_10_30_9_00_EEST</guid>
 </yweather:forecast>]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26578308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档