繁体   English   中英

我正在使用BeautifulSoup,我想获取img标签的alt值

[英]I am using BeautifulSoup and i want to get img tag's alt value

我想让一个棒球队今天的比赛中成为对手。

因此,我对此进行了编码。

该代码从网站上获取当今游戏的信息。

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)

而“ variable l”是当今游戏的信息。

img标签的alt值与团队的团队名称相反。

我要打印...帮帮我

由于您对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'
...
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM