Image 从URL列表下载图像
我在一个文本文件中有一个url列表。我希望将图像下载到一个特定的文件夹中,以及如何完成。chrome或任何其他程序中是否有可用于从url下载图像的插件Image 从URL列表下载图像,image,google-chrome,Image,Google Chrome,我在一个文本文件中有一个url列表。我希望将图像下载到一个特定的文件夹中,以及如何完成。chrome或任何其他程序中是否有可用于从url下载图像的插件 在计算机中创建文件夹 将图像URL的文本文件放在文件夹中 cd到该文件夹 使用wget-i images.txt 您将在文件夹中找到所有下载的文件 导入操作系统 导入时间 导入系统 导入URL库 从progressbar导入progressbar def get_raw_html(url): 版本=(3,0) 当前版本=系统版本信息 if cur
cd
到该文件夹wget-i images.txt
导入操作系统
导入时间
导入系统
导入URL库
从progressbar导入progressbar
def get_raw_html(url):
版本=(3,0)
当前版本=系统版本信息
if curr_version>=version:#如果Python的当前版本为3.0或更高版本
导入urllib.request#urllib库以提取网页
尝试:
标题={}
标题['User-Agent']=“Mozilla/5.0(X11;Linux i686)AppleWebKit/537.17(KHTML,如Gecko)Chrome/24.0.1312.27 Safari/537.17”
request=urllib.request.request(url,headers=headers)
resp=urllib.request.urlopen(请求)
respData=str(resp.read())
返回数据
例外情况除外,如e:
打印(str(e))
else:#如果当前版本的Python是2.x
导入urllib2
尝试:
标题={}
标题['User-Agent']=“Mozilla/5.0(X11;Linux i686)AppleWebKit/537.17(KHTML,如Gecko)Chrome/24.0.1312.27 Safari/537.17”
request=urlib2.request(url,headers=headers)
尝试:
response=urllib2.urlopen(请求)
URL错误除外:#处理SSL证书失败
context=ssl.\u创建\u未验证\u上下文()
响应=urlopen(请求,上下文=上下文)
#响应=urllib2.urlopen(请求)
raw_html=response.read()
返回原始html
除:
返回“未找到页面”
def下一个链接:
起始线=s.find('rg_di'))
如果start_line==-1:#如果没有找到链接,则给出一个错误!
结束_quote=0
link=“无链接”
返回链接,结束引用
其他:
start_line=s.find(''class=“rg_meta”')
start_content=s.find('ou',start_行+1)
end_content=s.find(',“ow”',start_content+1)
content\u raw=str(s[start\u content+6:end\u content-1])
返回内容\u原始内容,结束\u内容
定义所有链接(第页):
链接=[]
尽管如此:
链接,结束内容=下一个链接(第页)
如果link==“无链接”:
打破
其他:
links.append(link)#追加名为“links”的列表中的所有链接
#time.sleep(0.1)#计时器可用于降低图像下载请求的速度
页面=页面[结束内容:]
返回链接
def下载图片(链接、搜索关键字):
选择=输入(“是否保存链接?[y]/[n]:”)
如果选项=='y'或选项=='y':
#将所有链接写入测试文件。
f=open('links.txt','a')#打开名为links.txt的文本文件
对于链接中的链接:
f、 写(str(link))
f、 写入(“\n”)
f、 close()#关闭文件
num=输入(“输入要下载的图像数(最大100):”)
计数器=1
错误=0
搜索关键字=搜索关键字。替换(“%20”,“搜索”)
directory=search_关键字+'/'
如果不是os.path.isdir(目录):
os.makedirs(目录)
pbar=ProgressBar()
对于pbar中的链接(链接):
if counter=version:#如果Python的当前版本是3.0或更高版本
导入urllib.request#urllib库以提取网页
其他:
如果python的当前版本为2.x,则导入urllib2
搜索\关键字=输入(“输入搜索查询:”)
#下载图像链接
链接=[]
搜索关键字=搜索关键字。替换(“,“%20”)
url='1〕https://www.google.com/search?q=“+search_关键字+”&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch&sa=X&ei=XOSDVACXD8TASATIGE&ved=0CAcQ\u AUoAg”
原始html=(获取原始html(url))
链接=链接+(所有链接(原始html))
打印(“总图像链接=”+str(len(链接)))
打印(“\n”)
错误=下载图片(链接、搜索关键字)
打印(“下载完成。\n”+str(错误)+“下载时出错”)
搜索()
这需要制作成一个带有错误处理的函数,但它会重复下载图像以用于图像分类项目
导入请求
url=pd.read_csv('cat_urls.csv')#将url列表保存为数据框
行=[]
对于索引,在URL.ItErrors()中输入i:
行。追加(i[-1])
计数器=0
对于行中的i:
文件名='cat'+str(计数器)+'.jpg'
打印(文件名)
响应=请求。获取(i)
文件=打开(文件名,“wb”)
file.write(response.content)
file.close()文件
计数器+=1
在这篇文章中,我在unsplash.com中进行了搜索,它为我提供了一个URL列表,然后我保存了一些URL(由用户预定义)指向预定义文件夹。请查看。您好,欢迎使用stack over flow!通常为了使其更易于访问,您可以添加一些文本来描述和解释代码的作用;)完美!使用Linux的另一个优点是,在Windows中,当从Powershell启动wget时,wget将被一个内部Windows命令别名,该命令将行为稍有不同。如果您需要使用原始的wget,只需打开一个普通的cmd.exe shell并从那里启动它。我必须先brew安装wget
,但在那之后,这是一件轻而易举的事!非常感谢!
import os
import time
import sys
import urllib
from progressbar import ProgressBar
def get_raw_html(url):
version = (3,0)
curr_version = sys.version_info
if curr_version >= version: #If the Current Version of Python is 3.0 or above
import urllib.request #urllib library for Extracting web pages
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
request = urllib.request.Request(url, headers = headers)
resp = urllib.request.urlopen(request)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else: #If the Current Version of Python is 2.x
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
request = urllib2.Request(url, headers = headers)
try:
response = urllib2.urlopen(request)
except URLError: # Handling SSL certificate failed
context = ssl._create_unverified_context()
response = urlopen(req,context=context)
#response = urllib2.urlopen(req)
raw_html = response.read()
return raw_html
except:
return"Page Not found"
def next_link(s):
start_line = s.find('rg_di')
if start_line == -1: #If no links are found then give an error!
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+1)
end_content = s.find(',"ow"',start_content+1)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
def all_links(page):
links = []
while True:
link, end_content = next_link(page)
if link == "no_links":
break
else:
links.append(link) #Append all the links in the list named 'Links'
#time.sleep(0.1) #Timer could be used to slow down the request for image downloads
page = page[end_content:]
return links
def download_images(links, search_keyword):
choice = input("Do you want to save the links? [y]/[n]: ")
if choice=='y' or choice=='Y':
#write all the links into a test file.
f = open('links.txt', 'a') #Open the text file called links.txt
for link in links:
f.write(str(link))
f.write("\n")
f.close() #Close the file
num = input("Enter number of images to download (max 100): ")
counter = 1
errors=0
search_keyword = search_keyword.replace("%20","_")
directory = search_keyword+'/'
if not os.path.isdir(directory):
os.makedirs(directory)
pbar = ProgressBar()
for link in pbar(links):
if counter<=int(num):
file_extension = link.split(".")[-1]
filename = directory + str(counter) + "."+ file_extension
#print ("Downloading image: " + str(counter)+'/'+str(num))
try:
urllib.request.urlretrieve(link, filename)
except IOError:
errors+=1
#print ("\nIOError on Image" + str(counter))
except urllib.error.HTTPError as e:
errors+=1
#print ("\nHTTPError on Image"+ str(counter))
except urllib.error.URLError as e:
errors+=1
#print ("\nURLError on Image" + str(counter))
counter+=1
return errors
def search():
version = (3,0)
curr_version = sys.version_info
if curr_version >= version: #If the Current Version of Python is 3.0 or above
import urllib.request #urllib library for Extracting web pages
else:
import urllib2 #If current version of python is 2.x
search_keyword = input("Enter the search query: ")
#Download Image Links
links = []
search_keyword = search_keyword.replace(" ","%20")
url = 'https://www.google.com/search?q=' + search_keyword+ '&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg'
raw_html = (get_raw_html(url))
links = links + (all_links(raw_html))
print ("Total Image Links = "+str(len(links)))
print ("\n")
errors = download_images(links, search_keyword)
print ("Download Complete.\n"+ str(errors) +" errors while downloading.")
search()