【发布时间】:2019-03-14 14:10:16
【问题描述】:
我无法在任何地方找到这个特定问题的答案,而且我自己也无法弄清楚。
我有一个大的 HTML 文件,它是电子邮件的模板。我已将其作为文本文件读入并将值保存在变量 html_string 中我有几行包含语句,例如
<span style="color: #ff0000;"> {column_1}</span>
<span style="color: #ff0000;">{column_2}</span>
其中 {column_*} 部分将替换为其他值,例如名称。另一个问题建议使用诸如
之类的东西 soup = BeautifulSoup(html_string, features="html5lib")
target = soup.find_all(text=re.compile('^{column_$'))
print("Target:")
print(target)
for v in target:
# do something (this never gets accessed due to empty list)
返回
>>Target:
>> []
而我希望它会返回 {column_*} 的位置列表或其他我可以用来插入我自己的字符串的东西。
我为 re.compile(x) 部分尝试了几种不同的结构,但没有任何效果。
任何帮助将不胜感激!
编辑------ 出于某种原因,即使我导入了 bs4,也只有 findAll 函数会执行我需要的功能 - 通常建议不要使用它,因为 bs4 中的 find_all 会“做同样的事情” ¬(..)¬
soup = BeautifulSoup(html_string, features="html5lib")
target = soup.findAll(text=re.compile('{column_.}'))
for v in target:
v.replace_with(dictionary[str(v)])
body = str(soup)
【问题讨论】: