2016-05-11 12 views
4

Bild http://i.imgur.com/OigSBjF.pngWie Bilder von BeautifulSoup herunterladen?

Import fordert von BS4 Import BeautifulSoup

r = requests.get("xxxxxxxxx") 
soup = BeautifulSoup(r.content) 

for link in links: 
    if "http" in link.get('src'): 
     print link.get('src') 

ich die gedruckten URL erhalten, aber nicht wissen, wie mit ihm zu arbeiten.

+4

BeautifulSoup ist zum Parsen von HTML, 'Anfragen' sind Anfragen über HTTP. Das Herunterladen fällt in die letztere Kategorie. 'requests.get' diese URL und dann die Dokumentation zum Speichern des Hauptteils der Antwort. –

Antwort

4

Sie müssen auf die Festplatte herunterladen und schreiben:

import requests 
from os.path import basename 

r = requests.get("xxx") 
soup = BeautifulSoup(r.content) 

for link in links: 
    if "http" in link.get('src'): 
     lnk = link.get('src') 
     with open(basename(lnk), "wb") as f: 
      f.write(requests.get(lnk).content) 

Sie können auch ein wählen, um Ihre Tags zu filtern, um nur die, die mit http-Links zu erhalten:

for link in soup.select("img[src^=http]"): 
     lnk = link["src"] 
     with open(basename(lnk)," wb") as f: 
      f.write(requests.get(lnk).content) 
+0

Vielen Dank! –

+0

Keine Sorge, die Verwendung des Select-Ansatzes wäre der beste Ansatz, um die Tags zu filtern –

0

Während die andere Antworten sind vollkommen richtig.

Ich fand es wirklich langsam zu downloaden und weiß nicht den Fortschritt mit wirklich hochauflösenden Bildern.

Also, diesen gemacht.

from bs4 import BeautifulSoup 
import requests 
import subprocess 

url = "https://example.site/page/with/images" 
html = requests.get(url).text # get the html 
soup = BeautifulSoup(html, "lxml") # give the html to soup 

# get all the anchor links with the custom class 
# the element or the class name will change based on your case 
imgs = soup.findAll("a", {"class": "envira-gallery-link"}) 
for img in imgs: 
    imgUrl = img['href'] # get the href from the tag 
    cmd = [ 'wget', texUrl ] # just download it using wget. 
    subprocess.Popen(cmd) # run the command to download 
    # if you don't want to run it parallel; 
    # and wait for each image to download just add communicate 
    subprocess.Popen(cmd).communicate() 

Warnung: Es wird nicht auf Win/Mac arbeiten, wie es wget verwendet.

Bonus: Sie können den Fortschritt jedes Bildes sehen, wenn Sie nicht kommunizieren.