【问题标题】:cannot get the data within HTML tag无法获取 HTML 标记内的数据
【发布时间】:2019-02-09 04:10:21
【问题描述】:

无法获取 HTML 标签 "alt"= 中的数据

from bs4 import BeautifulSoup
import re
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="cflag"><img src="/ContentServer/jcbw/images/flag_JLC.gif?CV=L302R1g" alt="Japanese League Cup" title="Japanese League Cup" class="cfJLC"></div>
    <div class="cflag"><img src="/ContentServer/jcbw/images/flag_JLC.gif?CV=L302R1g" alt="Japanese League Cup" title="Japanese League Cup" class="cfJLC"></div>
    </div></div></div>""")

lines=soup.find_all('div')
line in lines:print(re.findall('\w+',line['alt'])[0])

【问题讨论】:

  • 您已经在使用 beautifulsoup 来获取 div。那你为什么要使用正则表达式?
  • for div in lines: imgs = div.find_all("img") for img in imgs: print(img['alt'])
  • 谢谢,亲爱的,解决了@DanielRoseman
  • 谢谢,亲爱的,解决了@WiktorStribiżew

标签: python regex beautifulsoup


【解决方案1】:

如果您只需要alt 值,那么最好使用img 标记而不是div 标记。也不需要使用正则表达式来提取alt

from bs4 import BeautifulSoup
import re
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="cflag"><img src="/ContentServer/jcbw/images/flag_JLC.gif?CV=L302R1g" alt="Japanese League Cup" title="Japanese League Cup" class="cfJLC"></div>
<div class="cflag"><img src="/ContentServer/jcbw/images/flag_JLC.gif?CV=L302R1g" alt="Japanese League Cup" title="Japanese League Cup" class="cfJLC"></div>
</div></div></div>""",'html.parser')

lines=soup.find_all('img')
for line in lines:
    print(line['alt'])

输出

日本联赛杯
日本联赛杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2013-09-01
    • 2013-03-15
    • 1970-01-01
    相关资源
    最近更新 更多