我遇到问题,我可以找到一种解决方法。我试图解析一个html页面,然后替换一个字符串,而使用Beautiful Soup。虽然这个过程看起来是正确的,并且当我打开新的html页面时我没有收到任何错误,但是我得到了一些我不想要的utf-8字符。工作代码如何避免在BeautifulSoup中使用replace_with打印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>
我认为我混淆了,编码和解码过程。有更多这方面知识的人可以详细阐述。我是一个编码和编码的初学者。
感谢您提前花时间和精力。
您要更换'forecast.tag'与处理字符串替换的整个'预测'元素。这与编码没有任何关系。 – mata
如果我不这样做,应该怎么做?这是我发现它工作的唯一途径。 ( – Thanos