使用 Beautiful Soup 从“img”标签中提取“src”属性

新手上路,请多包涵

考虑:

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

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

原文由 iDelusion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
1 个回答

您可以使用 Beautiful Soup 提取 HTML img 标签的 src 属性。在我的示例中, htmlText 包含 img 标签本身,但这也可以用于 URL,以及 urllib2

对于网址

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'])

对于带有 img 标签的文本

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'])

蟒蛇 3:

 from bs4 import BeautifulSoup as BSHTML
import urllib

page = urllib.request.urlopen('https://github.com/abushoeb/emotag')
soup = BSHTML(page)
images = soup.findAll('img')

for image in images:
    # Print image source
    print(image['src'])
    # Print alternate text
    print(image['alt'])

如果需要安装模块

# Python 3
pip install beautifulsoup4
pip install urllib3

原文由 Abu Shoeb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题