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

Finding Audio and Text between two <td> tags Python BeautifulSoup

我正在使用这个网站 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 模块而不是 bare-bones 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 字符串函数会让您的生活变得更加轻松 - 它们只会 return 一个(可能是空的)字符串。
  • .//table[@class="nemocards"] 仅当 table 的 class 属性为 精确 "nemocards" 时才会匹配。对于部分匹配,可以使用 .//table[contains(@class, "nemocards")] 之类的东西。

输出是这样的:

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