我有一个包含计算机游戏的链接,并且我想为每个游戏提取具有最高分辨率的产品 的图像,而不是所有img标签。到目前为止,我有:
#GET ALL IMG TAGS
img_tags = soup2.find_all('img')
#CREATE LIST WITH IMG TAGS
urls_img = [img['src'] for img in img_tags]
#CHECK EACH IMG TAG
for murl in urls_img:
filename = re.search(r'/([\w_-]+[.](jpg|png))$', murl)
if filename is not None:
with open(filename.group(1), 'wb') as f:
if 'http' not in murl:
murl = '{}{}'.format(site, murl)
#GET THE RESPONSE OF IMG URL
response = requests.get(murl)
if response.status_code == 200:
f.write(response.content)
答案 0 :(得分:2)
编辑:经过讨论,以下内容将获取初始产品网址(不包括占位符),并访问每个页面以查找最大的图像。最大的图像具有属性['data-large_image']
。
我使用Session
来提高重复使用连接的效率。
import requests
from bs4 import BeautifulSoup as bs
url = 'http://zegetron.gr/b2b/product-category/pc/?products-per-page=all'
images = []
with requests.Session() as s:
r = s.get(url)
soup = bs(r.content, 'lxml')
product_links = [item.select_one('a')['href'] for item in soup.select('.product-wrapper') if item.select_one('[src]:not(.woocommerce-placeholder)')]
for link in product_links:
r = s.get(link)
soup = bs(r.content, 'lxml')
images.append(soup.select_one('[data-large_image]')['data-large_image'])
以前的答案(基于所有产品的原始单个网址)
尝试以下操作,在每个列表中查找srcset
属性。如果存在,它将采用列出的最后一个src
链接(按升序排列),否则,将采用src
属性。
from bs4 import BeautifulSoup as bs
import requests
r = requests.get('http://zegetron.gr/b2b/product-category/pc/?products-per-page=all')
soup = bs(r.content, 'lxml')
listings = soup.select('.thumb-wrapper')
images = []
for listing in listings:
link = ''
if listing.select_one(':has([srcset])'):
links = listing.select_one('[srcset]')['srcset']
link = links.split(',')[-1]
link = link.split(' ')[1]
else:
if listing.select_one('[src]:not(.woocommerce-placeholder)'):
link = listing.select_one('img[src]')['src']
if link:
images.append(link)
print(images)
答案 1 :(得分:1)
我发现这也许更容易,并且解决了我的问题
for each_img_tag in img_tags:
width = each_img_tag.get('width')
if width is not None and int(width)>500:
urls_img.append(each_img_tag['src'])
即使我不知道它是否更快