我如何摆脱像 ' 这样的字符 出现而不是撇号?

nin*_*alf 6 python regex screen-scraping beautifulsoup web-scraping

可能的重复:
在 Python 中将 XML/HTML 实体转换为 Unicode 字符串

我正在尝试使用 Python 抓取网站。我导入并使用 urllib2、BeautifulSoup 和 re 模块。

response = urllib2.urlopen(url)
soup = BeautifulSoup(response)
responseString = str(soup)

coarseExpression = re.compile('<div class="sodatext">[\n]*.*[\n]*</div>')
coarseResult = coarseExpression.findall(responseString)

fineExpression = re.compile('<[^>]*>')
fineResult = []

for coarse in coarseResult:
    fine = fineExpression.sub('', coarse) 
    #print(fine)
    fineResult.append(fine)
Run Code Online (Sandbox Code Playgroud)

不幸的是,像撇号这样的字符以损坏的方式出现,就像这样 - ' ; 有办法避免这种情况吗?或者有什么方法可以轻松替换它们?

And*_*ark 5

您应该寻找以下有关实体转换的 BeautifulSoup 文档:

http://www.crummy.com/software/BeautifulSoup/documentation.html#Entity%20Conversion

  • 只是指出,BS 无法解码十六进制编码实体(`'`),但它可以很好地处理十进制编码实体(`'`)。所以,OP需要提前转换它们。 (2认同)