为什么Beautiful Soup忽略CDATA
我正在使用Beautiful Soup来处理雅虎天气API(python 2.7):
url = 'http://weather.yahooapis.com/forecastrss?w=2344116'
page=urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
但是在解析后的网址中,没有任何CDATA。为什么Beautiful Soup会忽略这个?我该如何防止忽略CDATA呢?
在xml中:
<img src="http://l.yimg.com/a/i/us/we/52/11.gif"/>
在解析后的页面中:
正如你所看到的,CDATA丢失了。
相关文章:
- 暂无相关问题
2 个回答
1
你为什么这么想要CDATA呢?从我看到的情况来看,下面几行有同样的数据,而且结构更清晰:
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
CDATA部分并不是被忽略了;它只是按照CDATA部分应该被处理的方式,被当作文本来处理:
>>> 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/>
你可以把那部分当作一个单独的页面来解析:
>>> 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
):
soup = BeautifulSoup(page, 'xml')
或者,更好的办法是使用feedparser
来解析RSS源。