如何使用beautifulSoup从网站上提取和下载所有图像?

use*_*817 8 python beautifulsoup

我试图从网址中提取和下载所有图像.我写了一个剧本

import urllib2
import re
from os.path import basename
from urlparse import urlsplit

url = "http://filmygyan.in/katrina-kaifs-top-10-cutest-pics-gallery/"
urlContent = urllib2.urlopen(url).read()
# HTML image tag: <img src="url" alt="some_text"/>
imgUrls = re.findall('img .*?src="(.*?)"', urlContent)

# download all images
for imgUrl in imgUrls:
    try:
        imgData = urllib2.urlopen(imgUrl).read()
        fileName = basename(urlsplit(imgUrl)[2])
        output = open(fileName,'wb')
        output.write(imgData)
        output.close()
    except:
        pass
Run Code Online (Sandbox Code Playgroud)

我不想提取这个页面的图像看到这个图像http://i.share.pho.to/1c9884b1_l.jpeg 我只是想获得所有图像而不点击"下一步"按钮我不知道怎么能我在"下一课"课程中得到了所有的照片.我应该在findall中做些什么改变?

Jon*_*han 20

以下内容应从给定页面中提取所有图像,并将其写入运行脚本的目录.

import re
import requests
from bs4 import BeautifulSoup

site = 'http://pixabay.com'

response = requests.get(site)

soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]


for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)
    with open(filename.group(1), 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative 
            # if it is provide the base url which also happens 
            # to be the site variable atm. 
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)
Run Code Online (Sandbox Code Playgroud)

  • “NoneType”对象没有属性“group” (3认同)

4d4*_*d4c -8

如果您只想要图片,那么您可以直接下载它们,甚至不需要废弃网页。它们都有相同的 URL:

http://filmygyan.in/wp-content/gallery/katrina-kaifs-top-10-cutest-pics-gallery/cute1.jpg
http://filmygyan.in/wp-content/gallery/katrina-kaifs-top-10-cutest-pics-gallery/cute2.jpg
...
http://filmygyan.in/wp-content/gallery/katrina-kaifs-top-10-cutest-pics-gallery/cute10.jpg
Run Code Online (Sandbox Code Playgroud)

如此简单的代码将为您提供所有图像:

import os
import urllib
import urllib2


baseUrl = "http://filmygyan.in/wp-content/gallery/katrina-kaifs-top-10-"\
      "cutest-pics-gallery/cute%s.jpg"

for i in range(1,11):
    url = baseUrl % i
    urllib.urlretrieve(url, os.path.basename(url))
Run Code Online (Sandbox Code Playgroud)

使用 Beautifulsoup,您必须单击或转到下一页才能废弃图像。如果您不想单独废弃每个页面,请尝试使用该类来刮擦它们,该类是shutterset_katrina-kaifs-top-10-cutest-pics-gallery