【问题标题】:How to modify html table content using beautifulsoup如何使用beautifulsoup修改html表格内容
【发布时间】:2021-04-21 00:51:07
【问题描述】:

您好,我正在尝试使用 beautifulsoup 和 API 请求更新汇合页面的表格内容之一。

这是我的代码。我能够找到并更新 td,但无法将更新后的 td 插入到 soup 变量中。

content=requests.get(address,headers=headers).text
soup=BeautifulSoup(content,'html.parser')
for td in soup.find_all('td'):
if td == "<td> i need to update this </td>:
td.replace_with("<td>updated</td>")

我需要将更新的 td 插入到汤变量中,所以当我搜索 soup.find_all('td') 时,我可以找到更新的而不是我需要更新它 我该怎么做?

谢谢

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    注意:解析 HTML 时不要使用正则表达式。我非常希望有解决这个问题的替代方法。但是,唉,我想不出一个。

    使用以下正则表达式,您可以找到每个没有附加属性的td 元素。 这可用于查找元素,但不要尝试从元素中实际获取信息

    &lt;td&gt;.*?&lt;/td&gt;

    然后您可以使用Pattern.sub() 方法将td 元素的每个实例替换为&lt;td&gt;updated&lt;/td&gt;

    import re
    
    import bs4
    import requests
    
    content = requests.get(address, headers=headers).text
    regex = re.compile(r"<td>.*?</td>")
    new_content = regex.sub("<td>update</td>", content)
    
    soup = bs4.BeautifulSoup(new_content, features="html.parser")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 2011-08-23
      • 2021-06-22
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多