【问题标题】:How to extract the first "src" attribute from a HTML tag如何从 HTML 标签中提取第一个“src”属性
【发布时间】:2021-11-24 04:40:02
【问题描述】:

假设我在下面有一个 HTML 标签:

target = <tr src="./sound/6/4-1-1.mp3"><td class="code">(4-1)a.</td><td class="sound"><audio controls=""><source src="./sound/6/4-1-1.mp3" type="audio/mpeg"/></audio></td><td class="text"><p class="ab">Na mapaspas a Subalis bunuaz busul tu laas.</p><p class="en">Subali is going to hit the plum.</p></td></tr>

我的理想输出:

<tr src="./sound/6/4-1-1.mp3">

我已经尝试使用以下代码:

import re
from bs4 import BeautifulSoup

soup = BeautifulSoup(target, 'lxml')
soup.find(src=re.compile('\.\w'))

但是,我的输出:

<source src="./sound/6/4-1-1.mp3" type="audio/mpeg"/>

如何才能得到上述理想的输出?

感谢您的帮助!!

【问题讨论】:

  • 您是否从某个网站或更多表格 html 中提取此内容?

标签: python python-3.x regex beautifulsoup


【解决方案1】:

你可以先找到tr,然后用regex'&lt;tr.*&gt;'在下面找到你想要的。

试试这个:

from bs4 import BeautifulSoup
import re

html="""
<tr src="./sound/6/4-1-1.mp3">
    <td class="code">(4-1)a.</td>
    <td class="sound"><audio controls="">
        <source src="./sound/6/4-1-1.mp3" type="audio/mpeg"/></audio>
    </td>
    <td class="text">
        <p class="ab">Na mapaspas a Subalis bunuaz busul tu laas.</p>
        <p class="en">Subali is going to hit the plum.</p>
    </td>
</tr>
"""
soup=BeautifulSoup(html,"lxml")
re.search(r'<tr.*>',str(soup.find("tr"))).group()

输出:

'<tr src="./sound/6/4-1-1.mp3">'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2017-10-14
    • 2013-04-06
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2017-07-05
    相关资源
    最近更新 更多