代码之家  ›  专栏  ›  技术社区  ›  aphexlog

正在尝试使用BeautifulSoup将新行附加到表体中的第一行

  •  0
  • aphexlog  · 技术社区  · 3 年前

    在将新行追加到表体()的第一行(标题行)时遇到问题。

    我的代码:

    from bs4 import BeautifulSoup  
    
    soup = BeautifulSoup(open('page_content.xml'), 'html.parser')
    
    # append a row to the first row in the table body
    row = soup.find('tbody').find('tr')
    row.append(soup.new_tag('tr', text='New Cell'))
    
    print(row)
    

    输出:

    <tr>
    <th>Version</th>
    <th>Jira</th>
    <th colspan="1">Date/Time</th>
    <tr text="New Cell"></tr></tr>
    

    输出应该是什么:

    <tr>
    <th>Version</th>
    <th>Jira</th>
    <th colspan="1">Date/Time</th>
    </tr>
    <tr text="New Cell"></tr>
    
    

    完整的xml文件是:

    <h1>Rental Agreement/Editor</h1>
    <table class="wrapped">
    <colgroup>
    <col/>
    <col/>
    <col/>
    </colgroup>
    <tbody>
    <tr>
    <th>Version</th>
    <th>Jira</th>
    <th colspan="1">Date/Time</th>
    <tr text="New Cell"></tr></tr>
    <tr>
    <td>1.0.1-0</td>
    <td>ABC-1234</td>
    <td colspan="1">
    <br/>
    </td>
    </tr>
    </tbody>
    </table>
    <p class="auto-cursor-target">
    <br/>
    </p>
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Andrej Kesely    3 年前

    你可以用 .insert_after :

    from bs4 import BeautifulSoup
    
    html_doc = """
    <table>
    <tr>
    <th>Version</th>
    <th>Jira</th>
    <th colspan="1">Date/Time</th>
    </tr>
    
    <tr>
    <td> something else </td>
    </tr>
    </table>
    """
    
    soup = BeautifulSoup(html_doc, "html.parser")
    
    row = soup.select_one("tr:has(th)")
    row.insert_after(soup.new_tag("tr", text="New Cell"))
    
    print(soup.prettify())
    

    印刷品:

    <table>
     <tr>
      <th>
       Version
      </th>
      <th>
       Jira
      </th>
      <th colspan="1">
       Date/Time
      </th>
     </tr>
     <tr text="New Cell">
     </tr>
     <tr>
      <td>
       something else
      </td>
     </tr>
    </table>