【问题标题】:Find and replace strings in HTML在 HTML 中查找和替换字符串
【发布时间】:2015-09-22 01:57:56
【问题描述】:

来自此 HTML 代码:

<p class="description" dir="ltr">Name is a fine man. <br></p>

我正在寻找使用以下代码替换“名称”:

target = soup.find_all(text="Name")
for v in target:
    v.replace_with('Id')

我想要的输出是:

<p class="description" dir="ltr">Id is a fine man. <br></p>

当我:

print target
[]

为什么找不到“名称”?

谢谢!

【问题讨论】:

  • 尝试使用str.replace(),你确定有一些与之匹配的文字吗?
  • 您没有带有文本Name 的元素。显示您的 HTML 以及您打算做什么。
  • 不太清楚你在问什么。首先,您的soup 是否找到任何text='Name'? replace_with 和 print target 之间还有代码吗?
  • @Daniel,我编辑了包括 HTML 在内的问题。
  • @PaulRooney,显然我的soup 没有找到text='Name' 并且中间没有代码,

标签: python html python-2.7 beautifulsoup


【解决方案1】:

它返回一个空列表,因为搜索这样的文本必须匹配标签中的整个文本,因此请改用正则表达式。

来自官方文档:BeautifulSoup - Search text

text 是一个参数,可让您搜索 NavigableString 对象 而不是标签。它的值可以是字符串、正则表达式、 列表或字典,True 或 None,或一个可调用的 NavigableString 对象作为其参数:

soup.findAll(text="one")
# [u'one']
soup.findAll(t ext=re.compile("paragraph"))
# [u'This is paragraph ', u'This is paragraph ']
soup.findAll(text=lambda(x): len(x) < 12)
# [u'Page title', u'one', u'.', u'two', u'.']

P.S.:已经讨论过的答案是here 和here。

【讨论】:

    【解决方案2】:

    HTML 中的文本节点包含除"Name" 之外的一些其他文本。在这种情况下,您需要放宽搜索条件以使用 contains 而不是 exact match,例如,使用正则表达式。然后您可以使用简单的string.replace()方法将匹配的文本节点替换为原始文本,除了"Name"部分应该替换为"Id",例如:

    from bs4 import BeautifulSoup
    import re
    
    html = """<p class="description" dir="ltr">Name is a fine man. <br></p>"""
    soup = BeautifulSoup(html)
    target = soup.find_all(text=re.compile(r'Name'))
    for v in target:
        v.replace_with(v.replace('Name','Id'))
    print soup
    

    输出:

    <html><body><p class="description" dir="ltr">Id is a fine man. <br/></p></body></html>
    

    【讨论】:

    • 效果很好!!非常感谢!
    猜你喜欢
    • 2013-02-18
    • 2011-08-22
    • 2019-06-24
    • 2016-01-13
    • 2011-10-23
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多