【问题标题】:BeautifulSoup - replace <tr> attributes based on <td> [duplicate]BeautifulSoup - 基于 <td> 替换 <tr> 属性 [重复]
【发布时间】:2021-09-14 14:45:42
【问题描述】:

我正在尝试做一些事情,如果父 &lt;tr&gt; 的子 &lt;td&gt;some string&lt;/td&gt; 与预定义的字符串匹配,则替换父 &lt;tr&gt; 标记类。

这是 html 的外观 -

<tr>
    <td>patterns</td>
    <td>password</td>
    <td>
        <ul>
            <li>some item</li>
        </ul>
    </td>
</tr>

我希望如果有任何子 &lt;td&gt; 匹配密码,则将父 &lt;tr&gt; 替换为 &lt;tr class="table-danger"&gt;

谢谢,

【问题讨论】:

  • 所以如果patterns 匹配password 然后替换patterns?
  • 对不起,我没有安全地包装要显示的 html - 它现在应该在问题中可见
  • 这能回答你的问题吗? Replace a tag with another tag in BeautifulSoup
  • 如果找到匹配项,是否要将整个 tr,放置到tr class="table-danger"&gt;?这将是整个 HTML。或者您还想保留 HTML 的其余部分?
  • 你能展示一个预期的完整输出的例子吗?

标签: python html beautifulsoup


【解决方案1】:

您可以使用:-soup-contains() 选择器来使用此示例。 (注意:对于旧版本的 BeautifulSoup,请改用:contains()

我已经评论了提供解释的代码:

from bs4 import BeautifulSoup


pattern = "LOOK_FOR_ME"

html = """
<html>
 <body>
  <tr>
   <td>
    LOOK_FOR_ME
   </td>
   <td>
    LOOK_FOR_ME
   </td>
   <td>
    <ul>
     <li>
      some item
     </li>
    </ul>
   </td>
  </tr>
 </body>
</html>
"""

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

match = soup.select_one(
    #  Select a `tr` with a preceding `td` that contains our pattern, with the next `td` containing our pattern
    f"tr > td:-soup-contains({pattern}) + td:-soup-contains({pattern})"
)

if match:
    # Replaces the `tr` with it's contents
    match.find_parent("tr").unwrap()
    # find the first `td` and insert before it the desired element
    match.find_previous("td").insert_before('tr class="table-danger">')

print(soup.prettify())

输出:

<html>
 <body>
  tr class="table-danger"&gt;
  <td>
   LOOK_FOR_ME
  </td>
  <td>
   LOOK_FOR_ME
  </td>
  <td>
   <ul>
    <li>
     some item
    </li>
   </ul>
  </td>
 </body>
</html>

文档:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2018-06-30
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    相关资源
    最近更新 更多