替换 html 中两个分隔符之间的字符串
Replace string between two delimiters in html
如何替换分隔符 href="" 之间的一些字符串?
<td><a href="https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n</a></td>
</tr>
我想替换这个:
href="https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n"
有了这个:
href="LINK"
为了快速而肮脏的方式,您可以使用 re.sub() 来匹配 'href' 标签并将其替换为您自己的标签:
import re
html = """<td><a href="https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n</a></td>
</tr>"""
re.sub('">.*<\/a>', '">LINK<\/a>" ' , html)
输出:
'<td><a href="LINK" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n</a></td>\n </tr>'
但请记住,不建议使用正则表达式解析 HTML,因为它可能有很多边缘情况。当我完全知道我的输入 HTML 的结构时,我只会将其用于快速而肮脏的方式。对于更专业的方法,您应该查看 HTML 解析器(例如 'beautifulsoup')。
如何替换分隔符 href="" 之间的一些字符串?
<td><a href="https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n</a></td>
</tr>
我想替换这个:
href="https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n"
有了这个:
href="LINK"
为了快速而肮脏的方式,您可以使用 re.sub() 来匹配 'href' 标签并将其替换为您自己的标签:
import re
html = """<td><a href="https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n</a></td>
</tr>"""
re.sub('">.*<\/a>', '">LINK<\/a>" ' , html)
输出:
'<td><a href="LINK" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uI1n</a></td>\n </tr>'
但请记住,不建议使用正则表达式解析 HTML,因为它可能有很多边缘情况。当我完全知道我的输入 HTML 的结构时,我只会将其用于快速而肮脏的方式。对于更专业的方法,您应该查看 HTML 解析器(例如 'beautifulsoup')。