BeautifulSoap获取一个div中所有img的多个元素和特定的类

2024-06-25 05:37:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用idpreviewImages获取image-file属性中的链接(相对链接是这样的)img标记中的img中的链接(我不想要src链接)。在

以下是HTML示例:

<div id="previewImages">
  <div class="thumb"> <a><img src="https://example.com/s/15.jpg" image-file="/image/15.jpg" /></a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/2.jpg" image-file="/image/2.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/0.jpg" image-file="/image/0.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/3.jpg" image-file="/image/3.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/4.jpg" image-file="/image/4.jpg" /> </a> </div>
</div>

我尝试了以下方法,但它只提供了第一个链接,而不是全部:

^{pr2}$

我怎样才能获得image-file属性中img标签的所有链接?在


Tags: httpsimagedivsrccomimg属性链接
3条回答

使用.findAll

例如:

from bs4 import BeautifulSoup

html = """<div id="previewImages">
  <div class="thumb"> <a><img src="https://example.com/s/15.jpg" image-file="/image/15.jpg" /></a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/2.jpg" image-file="/image/2.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/0.jpg" image-file="/image/0.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/3.jpg" image-file="/image/3.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/4.jpg" image-file="/image/4.jpg" /> </a> </div>
</div>"""

soup = BeautifulSoup(html, "html.parser")
images_box = soup.find('div', attrs={'id': 'previewImages'})
for link in images_box.findAll("img"):
    print link.get('image-file')

输出:

^{pr2}$

BeautifulSoup有方法.find_all()-检查docs。以下是在代码中使用它的方法:

import sys
import urllib2
from bs4 import BeautifulSoup

quote_page = sys.argv[1] # this should be the first argument on the command line
page = urllib2.urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')

images_box = soup.find('div', attrs={'id': 'previewImages'})
links = [img['image-file'] for img in images_box('img')]

print links   # in Python 3: print(links)

我认为将属性选择器传递给select时使用id会更快

from bs4 import BeautifulSoup as bs
html = '''
<div id="previewImages">
  <div class="thumb"> <a><img src="https://example.com/s/15.jpg" image-file="/image/15.jpg" /></a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/2.jpg" image-file="/image/2.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/0.jpg" image-file="/image/0.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/3.jpg" image-file="/image/3.jpg" /> </a> </div>
  <div class="thumb"> <a><img src="https://example.com/s/4.jpg" image-file="/image/4.jpg" /> </a> </div>
</div>
'''
soup = bs(html, 'lxml')
links = [item['image-file'] for item in soup.select('#previewImages [image-file]')]
print(links)

相关问题 更多 >