13

我无法显示内容,我的程序:

#! /usr/bin/python

import urllib
import re

url = "http://yahoo.com"
pattern = '''<span class="medium item-label".*?>(.*)</span>'''

website = urllib.urlopen(url)
pageContent = website.read()
result = re.findall(pattern, pageContent)

for record in result:
    print record

输出:

Masked teen killed by dad
First look in &#39;Hotel of Doom&#39;
Ex-NFL QB&#39;s sad condition
Reporter ignores warning
Romney&#39;s low bar for debates

所以问题是我应该在我的代码中包含什么才能将 ' 转换为字符

4

2 回答 2

17

在 Python2 中:

In [16]: text = 'Ex-NFL QB&#39;s sad condition'

In [17]: import HTMLParser

In [18]: parser = HTMLParser.HTMLParser()

In [19]: parser.unescape(text)
Out[19]: u"Ex-NFL QB's sad condition"

在 Python3 中:

import html.parser as htmlparser
parser = htmlparser.HTMLParser()
parser.unescape(text)
于 2012-09-28T19:30:05.833 回答
10

Python 3 的解决方案,

import html
html.unescape(text)
于 2019-02-13T18:34:28.123 回答