【问题标题】:Trying to loop through URL's and download images from these webpages尝试遍历 URL 并从这些网页下载图像
【发布时间】:2020-05-05 05:37:04
【问题描述】:

我有一个很好的 URL 结构,我想遍历 URL 并从 URL 下载所有图像。我正在尝试使用 BeautifulSoup 以及 requests 函数来完成工作。

这里是 URL - https://sixmorevodka.com/#&gid=0&pid={i},对于这个例子,我希望“i”从 1 到 100 进行迭代。

from bs4 import BeautifulSoup as soup
import requests, contextlib, re, os

@contextlib.contextmanager
def get_images(url:str):
  d = soup(requests.get(url).text, 'html.parser') 
  yield [[i.find('img')['src'], re.findall('(?<=\.)\w+$', i.find('img')['alt'])[0]] for i in d.find_all('a') if re.findall('/image/\d+', i['href'])]

n = 100 #end value
for i in range(n):
  with get_images(f'https://sixmorevodka.com/#&gid=0&pid={i}') as links:
    print(links)
    for c, [link, ext] in enumerate(links, 1):
       with open(f'ART/image{i}{c}.{ext}', 'wb') as f:
           f.write(requests.get(f'https://sixmorevodka.com{link}').content)

我想我要么在 Yield 行或在最后一个 write 行搞砸了。请有人帮帮我。我正在使用 Python 3.7

【问题讨论】:

    标签: python css python-3.x beautifulsoup


    【解决方案1】:

    在查看该网页的结构时,您的gid 参数无效。要亲自查看,请打开一个新选项卡并导航至 https://sixmorevodka.com/#&amp;gid=0&amp;pid=22

    您会注意到没有显示任何投资组合图像。 gid 可以是 1-5 的值,表示图片所属的网格。

    无论如何,您当前的抓取方法效率低下,并且会给网站带来过多的流量。相反,您只需要发出一次此请求,然后使用 ilb portfolio__grid__item 类选择器提取实际包含图像的 url。

    然后,您可以迭代并下载那些直接作为图像来源的 url。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2022-06-13
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多