使用 BeautifulSoup 从 img 标签中提取 src 属性 [英] Extract src attribute from img tag using BeautifulSoup

查看:102
本文介绍了使用 BeautifulSoup 从 img 标签中提取 src 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<a href=href"><img alt=一些"src=一些"/></a>

我想使用 BeautifulSoup 从图像(即 img)标签中提取源(即 src)属性.我使用 bs4 并且我不能使用 a.attrs['src'] 来获取 src,但我可以获取 href.我该怎么办?

解决方案

您可以使用 BeautifulSoup 提取 html imgsrc 属性标签.在我的示例中,htmlText 包含 img 标签本身,但这也可以与 urllib2 一起用于 URL.

对于网址

from BeautifulSoup 将 BeautifulSoup 导入为 BSHTML导入 urllib2page = urllib2.urlopen('http://www.youtube.com/')汤 = BSHTML(页面)图像 = 汤.findAll('img')对于图像中的图像:#打印图片来源打印图像['src']#打印替代文本打印图像['alt']

对于带有 img 标签的文本

from BeautifulSoup 将 BeautifulSoup 导入为 BSHTMLhtmlText = """<img src="https://src1.com/" <img src="https://src2.com/"/> """汤 = BSHTML(htmlText)图像 = 汤.findAll('img')对于图像中的图像:打印图像['src']

<div class="someClass">
    <a href="href">
        <img alt="some" src="some"/>
    </a>
</div>

I want to extract the source (i.e. src) attribute from an image (i.e. img) tag using BeautifulSoup. I use bs4 and I cannot use a.attrs['src'] to get the src, but I can get href. What should I do?

解决方案

You can use BeautifulSoup to extract src attribute of an html img tag. In my example, the htmlText contains the img tag itself but this can be used for a URL too along with urllib2.

For URLs

from BeautifulSoup import BeautifulSoup as BSHTML
import urllib2
page = urllib2.urlopen('http://www.youtube.com/')
soup = BSHTML(page)
images = soup.findAll('img')
for image in images:
    #print image source
    print image['src']
    #print alternate text
    print image['alt']

For Texts with img tag

from BeautifulSoup import BeautifulSoup as BSHTML
htmlText = """<img src="https://src1.com/" <img src="https://src2.com/" /> """
soup = BSHTML(htmlText)
images = soup.findAll('img')
for image in images:
    print image['src']

这篇关于使用 BeautifulSoup 从 img 标签中提取 src 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆