2016-10-27 196 views
-1

HTML片段:如何使用Beautifulsoup獲取img alt文本和data-src?

<span class="photo_tooltip" id="__w2_YFXobXt_link"> 
<a href="/profile/Smit-Soni-2" id="__w2_GDetCwt_link"> 
<img class="profile_photo_img" src="https://assets.ec.quoracdn.net/-images.placeholder_img.png96cbdb37c749e493.png" height="50" width="50" data-src="https://assets.ec.quoracdn.net/main-thumb-18048885-50-ujrumofdevpkaarfisuvjdtbihztxnta.jpeg" alt="Smit Soni" /> 
</a></span> 

我想提取所有從img class="profile_photo_imgalt文字和data-src。我的代碼:

ele = soup.find_all('img', class_='profile_photo_img') 
    for i in ele: 
     print i["data-src"] 
     print i["alt"] 

但它沒有打印任何東西。我怎樣才能得到想要的結果?

+2

你的代碼工作正常 – e4c5

+0

@ e4c5不,什麼都不打印 – slpcf

+0

@slpcf:請分享你如何創建對象'湯' –

回答

0

試試下面的代碼:

elements = soup.findAll('img', attrs={'class':'profile_photo_img'}) 
for element in elements: 
    print element['data-src'] 
    print element['alt'] 

還要確保湯是從HTML通過打印正確解析您正在搜索的元素之前

相關問題