Python 如何使用BeautifulSoup获得与正则表达式相同的结果?
我试图提取从中生成的Python 如何使用BeautifulSoup获得与正则表达式相同的结果?,python,beautifulsoup,Python,Beautifulsoup,我试图提取从中生成的content1中属性data-src-mp3的所有值(即链接) 该链接包含在中 一种方法是使用regrex'data-src-mp3=“(.*?”” 结果是 ['https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0037420.mp3', 'https://www.c
content1
中属性data-src-mp3
的所有值(即链接)
该链接包含在
中
一种方法是使用regrex'data-src-mp3=“(.*?””
结果是
['https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0037420.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0071410.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/fr_bachelier.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/63854.mp3']
我想问一下,如何使用BeautifulSoup
和结构
,在没有循环的情况下获得相同的结果
非常感谢你 您可以在使用
时组合选择器。选择:
mp3s = [tag.attrs['data-src-mp3'] for tag in soup.select('.cB.cB-def.dictionary.biling [data-src-mp3]')]
或
[data-src-mp3]
仅选择具有data-src-mp3
属性(具有任何值)的元素
只需将“data-src-mp3”
放在一个地方,即可实现以下功能:
mp3_tag = 'data-src-mp3'
mp3s = list(map(lambda tag: tag.attrs[mp3_tag],
soup.select('.cB.cB-def.dictionary.biling [{}]'.format(mp3_tag))))
这个解决方案一开始看起来可能更吓人,但比依赖错误的工具(例如解析HTML时使用正则表达式)要好得多。这太优雅了:))
mp3s = list(map(lambda tag: tag.attrs['data-src-mp3'],
soup.select('.cB.cB-def.dictionary.biling [data-src-mp3]')))
mp3_tag = 'data-src-mp3'
mp3s = list(map(lambda tag: tag.attrs[mp3_tag],
soup.select('.cB.cB-def.dictionary.biling [{}]'.format(mp3_tag))))