python - 使用 beautifulsoup 将标签插入到 html 中,并且值已经存在

标签 python beautifulsoup tags

我正在构建示例 How can I insert a new tag into a BeautifulSoup object?

import pandas
from bs4 import BeautifulSoup

a = [['1/2/2014', 'a', '6', 'z1'],
     ['1/2/2014', 'a', '3', 'z1'],
     ['1/3/2014', 'c', '1', 'x3'],
     ]
df = pandas.DataFrame.from_records(a[1:], columns=a[0])
soup = BeautifulSoup(df.to_html(header=False), 'lxml')

original_tag = soup.find_all('td')[4]
new_tag = soup.new_tag('FONT', COLOR='white')
original_tag.append(new_tag)
print(soup)
正如你所看到的。 1/3/2014位于标签 <FONT COLOR> 之外。我需要<FONT COLOR>要缠绕的标签 1/3/2014

最佳答案

您可以使用wrap所需标签的内容。

import pandas
from bs4 import BeautifulSoup

a = [['1/2/2014', 'a', '6', 'z1'],
     ['1/2/2014', 'a', '3', 'z1'],
     ['1/3/2014', 'c', '1', 'x3']]
df = pandas.DataFrame.from_records(a[1:], columns=a[0])
soup = BeautifulSoup(df.to_html(header=False), 'lxml')

original_tag = soup.find_all('td')[4]
new_tag = soup.new_tag('FONT', COLOR='white')
<strong>original_tag.contents[0].wrap(new_tag)</strong>
print(soup)

关于python - 使用 beautifulsoup 将标签插入到 html 中,并且值已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55079123/

相关文章:

python - 将 BeautifulSoup 与多处理池映射一起使用时的递归深度错误

c# - 标记数组 c# winforms

java - NLTK 找不到 Java 可执行文件

python - 将快速 Pandas 数据框写入 postgres

python - pyqt5 tablewidgets 检索数据

python,使用 Selenium 定位并单击特定按钮

python - 在python中替换字符串中的2个字符

python - 在 python 中使用 SSL 证书访问 protected 网站

python-3.x - 从html中的嵌入式脚本标签中提取数据

python - 转换自定义 XML 类语法的最佳方式