【问题标题】:Inserting tag within a tag using BeautifulSoup使用 BeautifulSoup 在标签内插入标签
【发布时间】:2023-03-24 21:30:02
【问题描述】:

我有以下 HTML 结构:

<BODY><tag1></tag1><tag2></tag2></BODY>

我需要使用 BeautifulSoup 在&lt;/BODY&gt; 之前插入一个表格。

我现在拥有的是:

re.sub(r'\s/BODY\s', '<Table>Test<Table></BODY>', BeautifulSoup(report, "lxml"))

我得到的错误是:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    execfile("C:\Users\My_PC\Desktop\Report.py")
  File "C:\Users\My_PC\Desktop\Report.py", line 10, in <module>
    re.sub(r'\s/BODY\s', '<Table>Test<Table></BODY>', BeautifulSoup(report, "lxml"))
  File "C:\Python27\lib\re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

任何帮助将不胜感激。

【问题讨论】:

  • re.sub() 需要字符串作为最后一个参数,但你已经给了 BeautifulSoup 对象。

标签: python html insert tags beautifulsoup


【解决方案1】:

您不需要正则表达式,您只需 append 表格到正文即可:

In [45]: soup = BeautifulSoup("<BODY><tag1></tag1><tag2></tag2></BODY>", "html.parser")

In [46]: soup.body.append(BeautifulSoup("<table>Test</table>","html.parser"))

In [47]: soup
Out[47]: <body><tag1></tag1><tag2></tag2><table>Test</table></body>

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 2020-02-26
    • 2020-11-06
    • 2014-10-02
    • 2018-09-24
    • 2021-08-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多