gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:18 25 4
gpt4 key购买 nike

我正在使用这个网站 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'}

关于python - 在两个 <td> 标签之间查找音频和文本 Python BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com