如何将图片从网站保存到本地文件夹 [英] How to save pictures from a website to a local folder
本文介绍了如何将图片从网站保存到本地文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将来自该网站的图片保存在一个文件夹中:
I'd need to save pictures from this website in a folder:
http://www.photobirdireland.com/garden-birds.html
我已经尝试过使用import os
I've tried by using import os
from lxml import html
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
class ImageScraper:
def __init__(self, url, download_path):
self.url = url
self.download_path = download_path
self.session = requests.Session()
def scrape_images(self):
html = urlopen(url)
bs4 = bs(html, 'html.parser')
images = bs4.find_all('img', {})
scraper = ImageScraper(url="http://www.photobirdireland.com/garden-birds.html")
scraper.scrape_images()
f = open('Users/Lu/Desktop/Images','wb') # folder
f.write(img)
f.close()
但是我没有得到任何结果或错误.
but I'm not getting any results or errors.
我很确定代码中有什么不起作用.
I'm pretty sure something's not working in the code.
请您看看,告诉我出什么问题了吗?
Can you have a look at it please and tell me what is wrong?
推荐答案
您的代码不完整,images = bs4.find_all('img', {})
示例
for image in images:
# get the img url
img_url = image.get('src').replace('\\', '/')
real_url = "http://www.photobirdireland.com/" + img_url
# get the image name
img_name = str(img_url.split('/')[-1])
# now download the image using - import urllib.request & import os
print("downloading {}".format(img_url))
urllib.request.urlretrieve(real_url, os.path.join(path, img_name))
完整代码应如下所示-
import os
import urllib.request
import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup as Bs
class ImageScraper:
def __init__(self, url, download_path):
self.url = url
self.download_path = download_path
self.session = requests.Session()
def scrape_images(self):
path = self.download_path
html = urlopen(self.url)
bs4 = Bs(html, 'html.parser')
images = bs4.find_all('img', {})
for image in images:
# get the img url
img_url = image.get('src').replace('\\', '/')
real_url = "http://www.photobirdireland.com/" + img_url
print(real_url)
# get the image name
img_name = str(img_url.split('/')[-1])
print(img_name)
print("downloading {}".format(img_url))
urllib.request.urlretrieve(real_url, os.path.join(path, img_name))
scraper = ImageScraper(
url="http://www.photobirdireland.com/garden-birds.html", download_path=r"D:\Temp\Images")
scraper.scrape_images()
这篇关于如何将图片从网站保存到本地文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文