【问题标题】:How can I search AND replace the text in a soup object?如何搜索和替换汤对象中的文本?
【发布时间】:2021-07-01 09:02:04
【问题描述】:

我有一个包含多行内容的 html 表格

<td>
              Bob Marley (bmarley@whatever.com)
</td>

我正在尝试仅用电子邮件地址的第一部分查找并替换此内容,并去掉空格。

<td>
bmarley
</td>

这是当前代码,成功匹配用户名部分。我不确定如何替换标签之间的内容。

name_regex = re.compile('(?<=())[a-zA-Z]+(?=@)')
soup = bs(open(page_source), 'lxml')
for row in soup.select(table_name)[1:]:
    name = re.search(name_regex,row.select_one('td:nth-of-type(2)').text.strip()).group()
    print(name)

【问题讨论】:

标签: python regex beautifulsoup replace


【解决方案1】:

您可以分配给.string属性,例如:

import re
from bs4 import BeautifulSoup


html_doc = """
<td>
              Bob Marley (bmarley@whatever.com)
</td>
<td>
              John Smith (j.smith@whatever.com)
</td>"""

soup = BeautifulSoup(html_doc, "html.parser")

name_regex = re.compile(r"\((.*)@")

for td in soup.select("td"):
    td.string = name_regex.search(td.text).group(1)

print(soup)

打印:

<td>bmarley</td>
<td>j.smith</td>

【讨论】:

    猜你喜欢
    • 2013-06-13
    • 2016-09-30
    • 2015-01-09
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多