我可以只从html打印[0]吗?
from bs4 import BeautifulSoup
soup=BeautifulSoup("""<div class="couponTable"><div id="tgCou1" class="tgCoupon couponRow"><span class="spBtnMinus"></span><!-- react-text: 67 -->Wednesday Matches<!-- /react-text --></div><div class="couponRow rAlt1 tgCou1" id="rmid20180905WED1"><img src="/ContentServer/jcbw/images/flag_JLC.gif?CV=L302R1g" alt="Japanese League Cup" title="Japanese League Cup" class="cfJLC"><img src="/ContentServer/jcbw/images/icon_tv-C661.gif?CV=L302R1g" alt="C661-i-CABLE 661 C601-i-CABLE 601" title="C661-i-CABLE 661 C601-i-CABLE 601"></span></span><img src="/football/info/images/btn_odds.gif?CV=L302R1g" alt="All Odds" title="All Odds"></a></div><div class="couponRow rAlt0 tgCou1" id="rmid20180905WED2"><img src="/ContentServer/jcbw/images/flag_JLC.gif?CV=L302R1g" alt="Japanese League Cup" title="Japanese League Cup" class="cfJLC"><img src="/ContentServer/jcbw/images/icon_tv-C662.gif?CV=L302R1g" alt="C662-i-CABLE 662 C602-i-CABLE 602" title="C662-i-CABLE 662 C602-i-CABLE 602"></span></span><img src="/football/info/images/btn_odds.gif?CV=L302R1g" alt="All Odds" title="All Odds"></a></div></div></div>""",'html.parser')
lines=soup.find_all('img')
for line in lines:
print(line['alt'])
输出
Japanese League Cup
C661-i-CABLE 661 C601-i-CABLE 601
All Odds
Japanese League Cup
C662-i-CABLE 662 C602-i-CABLE 602
All Odds
预期产量
Japanese League Cup
Japanese League Cup
答案 0 :(得分:2)
看看您对其他人的回应,您似乎不想要所有图像的替代文本,而只想要指定的图像。您给出的(虽然很小)示例的共同点是它们共享一个类。可能这就是您要寻找的东西吗?
lines=soup.find_all('img', class_='cfJLC')
for line in lines:
print(line['alt'])
输出:
Japanese League Cup
Japanese League Cup
答案 1 :(得分:1)
for line in lines:
print(line['alt'])
这将打印所有可用的详细信息。您只需要有关日本联赛杯的详细信息,就需要按照以下步骤操作,从图片中获取属性alt。
print(line.attrs['alt'])
答案 2 :(得分:0)
分别获取div,然后从中获取img标签。
for div in soup.find_all("ul", {"class": "couponRow"}):
print(div.find_all("img")[0].title)