HTMLParser和BeautifulSoup无法正确解码HTML实体

时间:2016-08-30 10:36:45

标签: python beautifulsoup html-entities html-parser

我正在尝试使用HTML entitiesHTML

HTMLParser源代码部分解码BeautifulSoup

但似乎两者似乎都没有完全奏效。即他们不解码斜杠。

我的Python版本为2.7.11 BeautifulSoup版本3.2.1

print 'ORIGINAL STRING: %s \n' % original_url_string

#clean up
try:
    # Python 2.6-2.7
    from HTMLParser import HTMLParser
except ImportError:
    # Python 3
    from html.parser import HTMLParser

h = HTMLParser()
url_string = h.unescape(original_url_string)

print 'CLEANED WITH html.parser: %s \n' % url_string

decoded = BeautifulSoup( original_url_string,convertEntities=BeautifulSoup.HTML_ENTITIES)

print 'CLEANED WITH BeautifulSoup: %s \n' % decoded.contents

给我一​​个输出:

ORIGINAL STRING: api.soundcloud.com%2Ftracks%2F277561480&show_artwork=true&maxwidth=1050&maxheight=1000 

CLEANED WITH html.parser: api.soundcloud.com%2Ftracks%2F277561480&show_artwork=true&maxwidth=1050&maxheight=1000 

CLEANED WITH BeautifulSoup: [u'api.soundcloud.com%2Ftracks%2F277561480&show_artwork=true&maxwidth=1050&maxheight=1000']

我在这里缺少什么?

在拔出网址之前,我是否应该尝试解码整个HTML页面?

使用Python有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您是要尝试从网址或网址的HTML中解码斜杠吗?

如果你试图解码斜杠,它们不是HTML entities,而是百分比编码的字符。

urllib拥有您需要的方法:

import urllib
urllib.unquote(original_url_string)
>>> 'api.soundcloud.com/tracks/277561480&show_artwork=true&maxwidth=1050&maxheight=1000'

如果您要解码html,首先必须get使用requestsurllib

等包