Skip to main content
 首页 » 编程设计

python之在两个 td> 标签之间查找音频和文本 Python BeautifulSoup

2024年11月24日8lexus

我正在使用这个网站 http://www.nemoapps.com/phrasebooks/hebrew .

例如,对于每个 td 元素,我想获取第一个 mp3 音频文件 /audio/mp3/HEBFND1_1395.mp3然后得到希伯来文文本 <strong>שרה שרה שיר שמח, שיר שמח שרה שרה</strong>和发音<strong>Sara shara shir sameaĥ, shir sameaĥ shara sara</strong>

以下代码可以实现我想要实现的目标,但还不够。

<source src="/audio/ogg/HEBFND1_1395.ogg" type="audio/ogg"> 
</source></source> 
[] 
[<div class="target1" lang="he"><strong>\u05e9\u05e8\u05d4 \u05e9\u05e8\u05d4 \u05e9\u05d9\u05e8 \u05e9\u05de\u05d7, \u05e9\u05d9\u05e8 \u05e9\u05de\u05d7 \u05e9\u05e8\u05d4 \u05e9\u05e8\u05d4</strong></div>, <div class="target2" lang="he-Latn"><strong>Sara shara shir samea\u0125, shir samea\u0125 shara sara</strong></div>, <div class="translation">Tongue Twister: Sara sings a happy song, a happy song Sara is singing</div>] 

这是我得到的示例输出。但我需要进入 source和 <div><strong>检索我想要的信息。

以下是我使用的代码。

from bs4 import BeautifulSoup 
import re 
import urllib 
 
_url = "http://www.nemoapps.com/phrasebooks/hebrew" 
soup = BeautifulSoup(urllib.urlopen(_url), features="lxml") 
_trs = soup.find_all('tr') 
for tr in _trs: 
    cells = tr.find_all('td', recursive=False) 
    for cell in cells: 
        audio = cell.find_all('audio') 
        div = cell.find_all('div') 
        for a in audio: 
            source = a.find_all('source', type='audio/mpeg') 
            for s in source: 
                print(s) 
        print(div) 
    print("++++++++") 

请告诉我是否有任何其他有效的方法来完成此操作。谢谢,

请您参考如下方法:

就我个人而言,我发现 BeautifulSoup 很难用而且很复杂,尤其是在按照最简单的规则以外的任何方式查找元素时。

lxml 模块可以很好地处理 HTML 源代码并提供 XPath 支持,这意味着查找元素多更容易且更灵活。

我也更喜欢使用 requests 模块而不是非常简单的 urllib。

import requests 
from lxml import etree 
 
resp = requests.get("http://www.nemoapps.com/phrasebooks/hebrew") 
 
htmlparser = etree.HTMLParser() 
tree = etree.fromstring(resp.text, htmlparser) 
 
for tr in tree.xpath('.//table[@class="nemocards"]/tr'): 
    data = { 
        'source': tr.xpath('string(.//source[@type="audio/mpeg"]/@src)'), 
        'hebrew': tr.xpath('normalize-space(.//div[@lang="he"])'), 
        'latin': tr.xpath('normalize-space(.//div[@lang="he-Latn"])'), 
        'translation': tr.xpath('normalize-space(.//div[@class="translation"])'), 
    } 
    print(data) 

注意事项:

  • string() 是一个 XPath 函数,它获取节点的文本内容(无论是属性节点还是元素节点都没有区别)。
  • normalize-space() 做同样的事情,但另外它会修剪多余的空格。
  • 当调用时没有这样的字符串转换(即像 tr.xpath('.//div[@lang="he"]'),你会得到一个(可能是空的)列表匹配元素的。因为你的目标是提取元素的文本内容,而这个任务在 Python 代码中更难完成,所以立即使用 XPath 字符串函数会让你的生活更容易 - 它们将简单地返回一个(可能是空的)字符串。
  • .//table[@class="nemocards"] 仅当表的类属性恰好为“nemocards”时才会匹配。对于部分匹配,可以使用 .//table[contains(@class, "nemocards")] 之类的内容。

输出是这样的:

{'source': '/audio/mp3/HEBFND1_0001.mp3', 'hebrew': 'שלום', 'latin': 'Shalom', 'translation': 'Hello'}