在 HTML 中查找和替换字符串
Find and replace strings in HTML
来自这个 HTML 代码:
<p class="description" dir="ltr">Name is a fine man. <br></p>
我正在寻找使用以下代码替换 "Name":
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
[]
为什么找不到 "Name"?
谢谢!
您 HTML 中的文本节点包含除 "Name"
之外的一些其他文本。在这种情况下,您需要放宽搜索条件以使用 contains 而不是 exact match,例如,通过使用正则表达式。然后你可以用原始文本替换匹配的文本节点,除了 "Name"
部分应该用 "Id"
替换,使用简单的 string.replace()
方法,例如:
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>
它returns是一个空列表,因为像这样搜索文本必须匹配标签中的整个文本,因此请改用正则表达式。
来自官方文档:BeautifulSoup - Search text
text is an argument that lets you search for NavigableString objects
instead of Tags. Its value can be a string, a regular expression, a
list or dictionary, True or None, or a callable that takes a
NavigableString object as its argument:
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 and here.
来自这个 HTML 代码:
<p class="description" dir="ltr">Name is a fine man. <br></p>
我正在寻找使用以下代码替换 "Name":
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
[]
为什么找不到 "Name"?
谢谢!
您 HTML 中的文本节点包含除 "Name"
之外的一些其他文本。在这种情况下,您需要放宽搜索条件以使用 contains 而不是 exact match,例如,通过使用正则表达式。然后你可以用原始文本替换匹配的文本节点,除了 "Name"
部分应该用 "Id"
替换,使用简单的 string.replace()
方法,例如:
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>
它returns是一个空列表,因为像这样搜索文本必须匹配标签中的整个文本,因此请改用正则表达式。
来自官方文档:BeautifulSoup - Search text
text is an argument that lets you search for NavigableString objects instead of Tags. Its value can be a string, a regular expression, a list or dictionary, True or None, or a callable that takes a NavigableString object as its argument:
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 and here.