簡體   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