【问题标题】:How to get the values of an attribute after content1.select() returns a list?content1.select() 返回列表后如何获取属性的值?
【发布时间】:2020-11-19 07:03:48
【问题描述】:

我正在尝试提取此url 的声音下载链接

from bs4 import BeautifulSoup
import requests

user_agent = {'User-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}

url = 'https://www.collinsdictionary.com/dictionary/english-french/graduate'
r = session.get(url, headers = headers)           
soup = BeautifulSoup(r.content, 'html.parser')

entry_name = soup.h2.text 
content1 = soup.select_one('.cB.cB-def.dictionary.biling')
sound_url = pandas.DataFrame({'LINK': [''], 'NAME': ['']})

temp1 = content1.select('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr')
print(temp1)

谁的结果

[<a class="hwd_sound sound audio_play_button icon-volume-up ptr" data-lang="en_GB" data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3" title="Pronunciation for "></a>, <a class="hwd_sound sound audio_play_button icon-volume-up ptr" data-lang="en_GB" data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0037420.mp3" title="Pronunciation for "></a>, <a class="hwd_sound sound audio_play_button icon-volume-up ptr" data-lang="en_GB" data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0071410.mp3" title="Pronunciation for "></a>, <a class="hwd_sound sound audio_play_button icon-volume-up ptr" data-lang="en_GB" data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/fr_bachelier.mp3" title="Pronunciation for "></a>, <a class="hwd_sound sound audio_play_button icon-volume-up ptr" data-lang="en_GB" data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/63854.mp3" title="Pronunciation for "></a>]

我的愿望是从列表temp1 的每个元素中提取属性data-src-mp3 的值。我尝试content1.select('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr').get('data-src-mp3') 但错误

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-48-357ee676f699> in <module>
     12 sound_url = pandas.DataFrame({'LINK': [''], 'NAME': ['']})
     13 
---> 14 temp1 = content1.select('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr').get('data-src-mp3')
     15 
     16 print(temp1)

C:\Anaconda3\lib\site-packages\bs4\element.py in __getattr__(self, key)
   2158     def __getattr__(self, key):
   2159         """Raise a helpful exception to explain a common code fix."""
-> 2160         raise AttributeError(
   2161             "ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key
   2162         )

AttributeError: ResultSet object has no attribute 'get'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

出现。您能否详细说明如何实现我的目标?

【问题讨论】:

    标签: python-3.x beautifulsoup css-selectors


    【解决方案1】:

    select() 返回您需要迭代列表的元素列表,然后使用element['attributename']

    temp1 = content1.select('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr')
    for item in temp1:
        print(item['data-src-mp3'])
    

    如果属性不存在,您将收到错误消息。我建议在选择元素时也包含该属性。

    temp1 = content1.select('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr[data-src-mp3]')
    for item in temp1:
        print(item['data-src-mp3'])
    

    temp1 = content1.select('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr[data-src-mp3]')
    print([item['data-src-mp3'] for item in temp1])
    

    【讨论】:

    • 我很惊讶我们别无选择,只能使用循环 for :(
    • 我想问一下是否有其他命令(不带循环)返回属性data-src-mp3的所有值。
    • @LAD : 如果你正在寻找单个元素,你可以使用 select_one()temp1 = content1.select_one('.hwd_sound.sound.audio_play_button.icon-volume-up.ptr[data-src-mp3]') print(temp1['data-src-mp3'])
    • 遗憾的是,我需要所有这些,而不仅仅是一个。
    • @LAD :您需要对其进行迭代,但是您可以将输出作为列表返回。检查更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多