【问题标题】:I am using BeautifulSoup and i want to get img tag's alt value我正在使用 BeautifulSoup,我想获得 img 标签 alt 值
【发布时间】:2017-08-10 17:43:08
【问题描述】:

我想得到一支棒球队今天比赛的对手。

所以我编码了这个。

此代码从网站获取今天的游戏信息。

from bs4 import BeautifulSoup
import datetime
import urllib.request

req = urllib.request.Request("http://www.hanwhaeagles.co.kr/html/game/1st_schedule_list1.asp")
data = urllib.request.urlopen(req).read()

bs = BeautifulSoup(data, 'html.parser')

l = bs.find_all('div')
idx = 0

for s in l:
    try:
        prop = s.get('class')
        if prop != None and prop[0] == "box" and len(prop) == 2:
            l = s
            break
    except UnicodeEncodeError:
        print("Error")
    finally:
        idx += 1

print(l)

“变量 l”是今天的游戏信息。

img 标签的 alt 值是对方球队的球队名称。

我想打印它...帮帮我

【问题讨论】:

    标签: python bs4


    【解决方案1】:

    因为您对box 类中存在的数据更感兴趣。您可以直接提取该类并进一步处理它:

    from bs4 import BeautifulSoup
    import datetime
    import urllib.request
    
    req = urllib.request.Request("http://www.hanwhaeagles.co.kr/html/game/1st_schedule_list1.asp")
    data = urllib.request.urlopen(req).read()
    bs = BeautifulSoup(data, 'html.parser')
    
    for item in bs.select('.box'):
        team_name = item.find('img')['alt']
        print(team_name)
    
    'NC'
    'NC'
    ...
    

    【讨论】:

    • team_name = chunck[0].find('img')['alt'] IndexError: list index out of range
    • 我打印了chuck,它的值是[]
    • 我已经根据你的代码编辑了答案,现在试试
    • 谢谢。现在我知道了选择方法。
    • 今天的游戏是.box.today 所以我把bs.select('.box') 编辑成bs.select('.box.today'),我解决了这个问题。
    【解决方案2】:
    from bs4 import BeautifulSoup
    import urllib.request
    
    req = urllib.request.Request("http://www.hanwhaeagles.co.kr/html/game/1st_schedule_list1.asp")
    data = urllib.request.urlopen(req).read()
    
    bs = BeautifulSoup(data, 'html.parser')
    
    table = bs.find('table')
    
    for tr in table.find_all('tr'):
        for td in tr.find_all('td'):
            if td.find('img'):
                if 'alt' in td.find('img').attrs:
                    print(td.find('img')['alt'])
    

    输出:

    NC
    NC
    NC
    KIA
    KIA
    KIA
    두산
    두산
    삼성
    삼성
    넥센
    넥센
    SK
    SK
    NC
    NC
    롯데
    롯데
    KT
    KT
    KIA
    KIA
    SK
    SK
    LG
    LG
    KT
    

    【讨论】:

    • 我做到了。谢谢!
    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 2018-01-07
    • 2015-04-26
    • 1970-01-01
    • 2020-08-15
    • 2021-09-12
    • 2020-11-20
    • 1970-01-01
    相关资源
    最近更新 更多