如何在Python 3.1中以字符串形式隐藏HTML实体?

Vol*_*Rig 59 html python curl entities python-3.x

我已经四处寻找并且只找到了python 2.6及更早版本的解决方案,没有关于如何在python 3.X中执行此操作.(我只能访问Win7盒子.)

我必须能够在3.1中执行此操作,并且最好不使用外部库.目前,我安装了httplib2并访问命令提示符curl(这就是我获取页面源代码的方式).不幸的是,curl不解码html实体,据我所知,我找不到在文档中解码它的命令.

是的,我试图让美丽的汤工作,很多时候没有成功3.X. 如果您可以在MS Windows环境中提供有关如何在python 3中使用它的EXPLICIT说明,我将非常感激.

所以,要清楚,我需要将这样Suzy & John的字符串转换成这样的字符串:"Suzy&John".

unu*_*tbu 163

你可以使用函数html.unescape:

Python3.4 +中(感谢JF Sebastian的更新):

import html
html.unescape('Suzy & John')
# 'Suzy & John'

html.unescape('"')
# '"'
Run Code Online (Sandbox Code Playgroud)

Python3.3或更早版本中:

import html.parser    
html.parser.HTMLParser().unescape('Suzy & John')
Run Code Online (Sandbox Code Playgroud)

Python2中:

import HTMLParser
HTMLParser.HTMLParser().unescape('Suzy & John')
Run Code Online (Sandbox Code Playgroud)

  • 从Python 3.4开始,它被公开为`html.escape()` (2认同)

Gre*_*ill 15

你可以用它xml.sax.saxutils.unescape来达到这个目的.该模块包含在Python标准库中,可在Python 2.x和Python 3.x之间移植.

>>> import xml.sax.saxutils as saxutils
>>> saxutils.unescape("Suzy & John")
'Suzy & John'
Run Code Online (Sandbox Code Playgroud)


Der*_*old 6

显然我没有足够的声誉做任何事情,但发布这个.unutbu的答案并没有取消引用.我发现的唯一的事情就是这个功能

import re
from htmlentitydefs import name2codepoint as n2cp

def decodeHtmlentities(string):
    def substitute_entity(match):        
        ent = match.group(2)
        if match.group(1) == "#":
            return unichr(int(ent))
        else:
            cp = n2cp.get(ent)
            if cp:
                return unichr(cp)
            else:
                return match.group()
    entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
    return entity_re.subn(substitute_entity, string)[0]
Run Code Online (Sandbox Code Playgroud)

我是从这个页面得到的.