【问题标题】:Python Beautiful Soup - finding a string that contains special charactersPython Beautiful Soup - 查找包含特殊字符的字符串
【发布时间】:2022-07-16 23:15:08
【问题描述】:

这是我的代码:

soup = BeautifulSoup("<html><body>BLAR fff11 &pound; </body></html>", 'html.parser')
for z in soup.find_all(text=re.compile('&pound;')):
    print(z)

由于某种原因没有返回任何内容,但是如果我更改示例 html 和我的 find 语句中的特殊字符,它会起作用:

soup = BeautifulSoup("<html><body>BLAR fff11 pound </body></html>", 'html.parser')
for z in soup.find_all(text=re.compile('pound')):
    print(z)

输出为:BLAR fff11 磅

有谁知道我哪里出错了,以及如何找到带有特殊字符的字符串?

谢谢

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

当您从 HTML 构造 BeautifulSoup 对象时,HTML 实体将转换为相应的 Unicode 字符。

因此,要搜索这样的字符,请使用字符本身,而不是其等效的 HTML 实体。在您的示例中使用 HTML,下面的代码...

from bs4 import BeautifulSoup
import re
soup = BeautifulSoup("<html><body>BLAR fff11 &pound; </body></html>", 'html.parser')
for z in soup.find_all(text=re.compile('£')):  # Actual '£' character, not '&pound;'
    print(z)

...打印:

BLAR fff11 £ 

在 BeautifulSoup 的 v3 中可以绕过这种转换,但在 v4 中则不行 ("An incoming HTML or XML entity is always converted into the corresponding Unicode character.")

如果您想在将 BeautifulSoup 对象转换为字符串时恢复 HTML 实体,specifying formatter="html" 仍然可以做到这一点。

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 2021-08-15
    • 2014-11-25
    • 2020-12-25
    • 2019-04-16
    • 2010-12-20
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多