【问题标题】:How to use BeautifulSoup to get the same result obtained by regex?如何使用 BeautifulSoup 获得与正则表达式相同的结果?
【发布时间】:2020-07-29 18:16:41
【问题描述】:

我正在尝试从url 生成的content1 中提取属性data-src-mp3 的所有值(链接)。

链接包含在<a class="hwd_sound sound audio_play_button icon-volume-up ptr" title="Pronunciation for " data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3" data-lang="en_GB"></a>中。

一种方法是使用正则表达式'data-src-mp3="(.*?)"'

import requests
session = requests.Session()
from bs4 import BeautifulSoup
import re

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
url = 'https://www.collinsdictionary.com/dictionary/english-french/graduate'
r = session.get(url, headers = headers)           
soup = BeautifulSoup(r.content, 'html.parser')

content1 = soup.select_one('.cB.cB-def.dictionary.biling').contents
output = re.findall('data-src-mp3="(.*?)"', str(content1))

print(output)

结果是

['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和结构<a class="hwd_sound sound audio_play_button icon-volume-up ptr" title="Pronunciation for " data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3" data-lang="en_GB"></a>在没有循环的情况下获得相同的结果。

非常感谢!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    使用.select时可以组合选择器:

    mp3s = [tag.attrs['data-src-mp3'] for tag in soup.select('.cB.cB-def.dictionary.biling [data-src-mp3]')]
    

    mp3s = list(map(lambda tag: tag.attrs['data-src-mp3'],
                    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 时的正则表达式)要好得多。

    【讨论】:

    • 这太优雅了:))))
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 2019-08-28
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多