BeautifulGroup在XML b中找不到标记

2024-06-16 09:52:12 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试解析XML文件时,得到了内容描述,其中包含一个标记和一个img标记。但如果我试图在描述中找到一个标签-我一个也没有。在

from bs4 import BeautifulSoup
import requests

url = 'http://lavagra.livejournal.com/data/rss&count=10&ranked=newest&similar=true'


r = requests.get(url)

soup = BeautifulSoup(r.content, 'xml')
items = soup.find_all('item')
# print(items)
for item in items:
    description = item.find('description')
    print(description)
    link = description.find('a')
    print(link)

<a data-flickr-embed="true" href="https://www.flickr.com/photos/10338828@N00/31295110800/in/dateposted-public/" title="puerto02"><img src="https://c1.staticflickr.com/1/489/31295110800_93f48b9bd2_o.jpg" width="1289" height="856" alt="puerto02"></a><br /><br />Ситуация с арестом блоггера Александра Лапшина <span class="ljuser i-ljuser i-ljuser-type-P " data-ljuser="puerrtto" lj:user="puerrtto" ><a href="http://puerrtto.livejournal.com/profile" target="_self" class="i-ljuser-profile" ><img class="i-ljuser-userhead" src="http://l-stat.livejournal.net/img/userinfo.gif?v=17080?v=144.7" /></a><a href="http://puerrtto.livejournal.com/" class="i-ljuser-username" target="_self"
><b>puerrtto</b></a></span>в Беларуси вступила в критическую фазу. Через несколько дней его скорее всего экстрадируют в Азербайджан. Предвижу восторженное улюлюканье в комментариях. Только хочу спросить всех кто не равнодушен к этому делу - не кажется ли Вам, что союзное государство России с Беларусью лишь блеф? ... None


Tags: 标记comhttpimgdataitemsdescriptionfind
2条回答
for item in items:
    description = item.find('description')
    # description will retrun a block of text, you should make a new soup based on this text.
    des_soup = BeautifulSoup(description.text, 'lxml')
    link = des_soup.find('a').get('href')
    print(link)

输出:

^{pr2}$

description标记是一个仅包含HTML文本块的单个标记。 如果您想在这个HTML文本上使用find(),您应该基于它制作一个新的soup。在

实际上,<description>标记中的内容是用html实体编码的,例如&lt;是{},因此在解析之前需要对这些实体进行取消转义。您可以使用内置的HTMLParser.HTMLParser().unescape()来完成这项工作。在

import requests
import HTMLParser
from bs4 import BeautifulSoup as soup

response = requests.get('http://lavagra.livejournal.com/data/rss&count=10&ranked=newest&similar=true')
html = soup(HTMLParser.HTMLParser().unescape(response.text), 'lxml')

items = html.find_all('item')

for item in items:
    description = item.find('description')
    print description
    link = description.find('a')
    print link

输出示例:

^{pr2}$

相关问题 更多 >