我遇到了问题,我可以找到解决方法。我正在尝试解析 html 页面,然后替换字符串,同时使用 Beautiful Soup 。虽然这个过程看起来是正确的,并且当我打开新的 html 页面时我没有收到任何错误,但我在里面得到了一些我不想要的 utf-8 字符。
工作代码示例:
#!/usr/bin/python
import codecs
from bs4 import BeautifulSoup
html_sample = """
<!DOCTYPE html>
<html><head lang="en"><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body>
<div class="date">LAST UPDATE</div>
</body>
</html>
"""
try:
my_soup = BeautifulSoup(html_sample.decode('utf-8'), 'html.parser') # html5lib or html.parser
forecast = my_soup.find("div", {"class": "date"})
forecast.tag = unicode(forecast).replace('LAST UPDATE', 'TEST')
forecast.replace_with(forecast.tag)
# print(my_soup.prettify())
f = codecs.open('test.html', "w", encoding='utf-8')
f.write(my_soup.prettify().encode('utf-8'))
f.close()
except UnicodeDecodeError as e:
print('Error, encoding/decoding: {}'.format(e))
except IOError as e:
print('Error Replacing: {}'.format(e))
except RuntimeError as e:
print('Error Replacing: {}'.format(e))
并在新的html页面中输出带有utf-8字符的内容:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1" name="viewport"/>
</meta>
</head>
<body>
<div class="date">TEST</div>
</body>
</html>
我认为我混淆了编码和解码过程。对这一领域有更多了解的人可以详细说明。我是编码和编码方面的初学者。
感谢您提前投入的时间和精力。
最佳答案
这里无需讨论编码。您可以通过设置 element.string
来替换 Beautiful Soup 元素的文本内容,如下所示:
from bs4 import BeautifulSoup
html_sample = """
<!DOCTYPE html>
<html><head lang="en"><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body>
<div class="date">LAST UPDATE</div>
</body>
</html>
"""
soup = BeautifulSoup(html_sample)
forecast = soup.find("div", {"class": "date"})
forecast.string = 'TEST'
print(soup.prettify())
输出
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
</head>
<body>
<div class="date">
TEST
</div>
</body>
</html>
关于python - 如何使用replace_with避免在BeautifulSoup中打印utf-8字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34811396/