2013-07-03 1 views
1

XML RSS 피드를 읽으려면 BeautifulSoup 4 (bs4)를 사용하고 다음 항목을 발견했습니다. 나는 <content:encoded><![CDATA[...]]</content> 태그 안에 내용을 읽을려고 : 내가 알고있는 것처럼,이 형식은BeautifulSoup를 사용하여 <content : encoded> 태그를 읽는 중 4

<item> 
    <title>Foobartitle</title> 
    <link>http://www.acme.com/blah/blah.html</link> 
    <category><![CDATA[mycategory]]></category> 
    <description><![CDATA[The quick brown fox jumps over the lazy dog]]></description> 
    <content:encoded> 
     <![CDATA[<p><img class="feature" src="http://www.acme.com/images/image.jpg" alt="" /></p>]]> 
    </content:encoded> 
</item> 

RSS content module의 일부이며 매우 일반적입니다.

<content:encoded> 태그를 분리 한 다음 CDATA 내용을 읽으 려합니다. 의심의 여지를 피하기 위해 결과는 <p><img class="feature" src="http://www.acme.com/images/image.jpg" alt="" /></p>입니다.

나는 this, thisthis 유래 게시물을 검토 한하지만 나는 그들이 직접 내 경우에 관련되지 않기 때문에 작업을 수행하는 방법을 알아 내려고 할 수 없었습니다.

나는 bs4와 함께 lxml XML 파서를 사용하고 있습니다.

제안 사항? 감사!

+0

bs4가 여기에 설명 된대로 CDATA 태그를 제거하기 때문에 참조하는 대답이 작동하지 않는 이유는 http://stackoverflow.com/questions/16426507/can-cdata-sections-be-preserved-by -beautifulsoup? rq = 1이고 스프가 만들어진 후 CDATA에 대한 모든 언급은 무의미합니다. BeautifulSoup 3에서는이 작업을 수행하지 않으므로 참조에서 주어진 대답이 해당 버전에 유용합니다. – ojs

답변

3
from bs4 import BeautifulSoup 

doc = ... 
soup = BeautifulSoup(doc, "xml") # Directs bs to use lxml 

흥미롭게도, BeautifulSoup로/LXML는 content:encoded 단순히 encoded에서 눈에 띄게, 주위의 태그를 변경합니다.

>>> print soup 
<?xml version="1.0" encoding="utf-8"?> 
<item> 
<title>Foobartitle</title> 
<link>http://www.acme.com/blah/blah.html</link> 
<category>mycategory</category> 
<description>The quick brown fox jumps over the lazy dog</description> 
<encoded> 
     &lt;p&gt;&lt;img class="feature" src="http://www.acme.com/images/image.jpg" alt="" /&gt;&lt;/p&gt; 
    </encoded> 
</item> 

거기에서 어린이를 통해 구문 분석하면됩니다.

for encoded_content in soup.findAll("encoded"): 
    for child in encoded_content.children: 
     print child 

그 결과는 <p><img class="feature" src="http://www.acme.com/images/image.jpg" alt="" /></p>입니다. 참고, 이것은 bs4.element.NavigableString의 인스턴스 인 것 같습니다. 링크 된 답변과 같은 CData는 아닙니다.

+0

Oliver, 빠른 응답에 감사드립니다! 이상한 내용 : encoded -> encoded tag change는 제가 누락 된 부분이었습니다. – tohster

관련 문제