使用类从HTML获取元素

2024-09-29 00:11:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的HTML

<div class="ui_columns is-gapless is-mobile">
    <div class="ui_column is-4 providerLogoOuter">
        <span class="providerLogoInner" title=""><imgsrc="https://static.tacdn.com/img2/branding/hotels/Hoteiscom_384x164.png" class="providerImg" alt="Hoteis.com">

但我只需要酒店网站“从alt=

我想用BeautifulSoap得到它,但是我怎样才能得到这个元素呢?你知道吗

name_player = soup.find_all(class_='providerLogoInner')[0]

它不返回任何元素


Tags: columnsdivcom元素uiishtmlcolumn
2条回答

那是格式错误的html还是打字错误?你知道吗

html="""
<div class="ui_columns is-gapless is-mobile">
<div class="ui_column is-4 providerLogoOuter">
<span class="providerLogoInner" title=""><imgsrc="https://static.tacdn.com/img2/branding/hotels/Hoteiscom_384x164.png" class="providerImg" alt="Hoteis.com">
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html,'html5lib')
print(soup.find(class_='providerImg')['alt'])

输出:

Hoteis.com

你可以做:

from bs4 import BeautifulSoup


raw = '''
<div class="ui_columns is-gapless is-mobile">
    <div class="ui_column is-4 providerLogoOuter">
        <span class="providerLogoInner" title=""><imgsrc="https://static.tacdn.com/img2/branding/hotels/Hoteiscom_384x164.png" class="providerImg" alt="Hoteis.com">
'''

soup = BeautifulSoup(raw,'html5lib')

hotel_lnk = soup.find('span',{'class':'providerLogoInner'}).next['alt']

print(hotel_lnk)

#'Hoteis.com'

相关问题 更多 >