本文的目的是介绍如何使用urllib2在python中下载zip文件?的详细情况,特别关注pythonurl下载的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解如何使
本文的目的是介绍如何使用urllib2在python中下载zip文件?的详细情况,特别关注python url下载的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解如何使用urllib2在python中下载zip文件?的机会,同时也不会遗漏关于403禁止使用Urllib2 [Python]、Android Java-如何从URL下载zip文件?、Python 2.x 中如何使用urllib.quote()函数对URL进行编码、Python 2.x 中如何使用urllib2模块发送HTTP请求的知识。
本文目录一览:- 如何使用urllib2在python中下载zip文件?(python url下载)
- 403禁止使用Urllib2 [Python]
- Android Java-如何从URL下载zip文件?
- Python 2.x 中如何使用urllib.quote()函数对URL进行编码
- Python 2.x 中如何使用urllib2模块发送HTTP请求
如何使用urllib2在python中下载zip文件?(python url下载)
两部分的问题。我正在尝试从互联网档案中下载多个已存档的Cory
Doctorow播客。我的iTunes提要中未包含的旧版本。我已经编写了脚本,但是下载的文件格式不正确。
问题1-如何更改以下载zip mp3文件?问题2-将变量传递到URL的更好方法是什么?
# and the base url.def dlfile(file_name,file_mode,base_url): from urllib2 import Request, urlopen, URLError, HTTPError #create the url and the request url = base_url + file_name + mid_url + file_name + end_url req = Request(url) # Open the url try: f = urlopen(req) print "downloading " + url # Open our local file for writing local_file = open(file_name, "wb" + file_mode) #Write to our local file local_file.write(f.read()) local_file.close() #handle errors except HTTPError, e: print "HTTP Error:",e.code , url except URLError, e: print "URL Error:",e.reason , url# Set the range var_range = range(150,153)# Iterate over image rangesfor index in var_range: base_url = ''http://www.archive.org/download/Cory_Doctorow_Podcast_'' mid_url = ''/Cory_Doctorow_Podcast_'' end_url = ''_64kb_mp3.zip'' #create file name based on known pattern file_name = str(index) dlfile(file_name,"wb",base_url
该脚本是从这里改编的
答案1
小编典典这是我处理URL构建和下载的方式。我确保将文件命名为url的基本名称(后跟斜杠后的最后一位),并且我还使用该with
子句来打开要写入的文件。这使用了一个很好的ContextManager,因为它将在该块退出时关闭该文件。另外,我使用模板来构建URL字符串。urlopen
不需要请求对象,只需一个字符串。
import osfrom urllib2 import urlopen, URLError, HTTPErrordef dlfile(url): # Open the url try: f = urlopen(url) print "downloading " + url # Open our local file for writing with open(os.path.basename(url), "wb") as local_file: local_file.write(f.read()) #handle errors except HTTPError, e: print "HTTP Error:", e.code, url except URLError, e: print "URL Error:", e.reason, urldef main(): # Iterate over image ranges for index in range(150, 151): url = ("http://www.archive.org/download/" "Cory_Doctorow_Podcast_%d/" "Cory_Doctorow_Podcast_%d_64kb_mp3.zip" % (index, index)) dlfile(url)if __name__ == ''__main__'': main()
403禁止使用Urllib2 [Python]
url = 'https://www.instagram.com/accounts/login/ajax/' values = {'username' : 'User','password' : 'Pass'} #'User-agent','' data = urllib.urlencode(values) req = urllib2.Request(url,data,headers={'User-Agent' : "Mozilla/5.0"}) con = urllib2.urlopen( req ) the_page = response.read()
有没有人对此有任何想法?我一直收到错误“403禁止”.
它可能的instagram有一些东西不允许我通过python连接(我不想通过他们的API连接).到底发生了什么,有没有人有任何想法?
谢谢!
编辑:添加更多信息.
我得到的错误就是这个
This page Could not be loaded. If you have cookies disabled in your browser,or you are browsing in Private Mode,please try enabling cookies or turning off Private Mode,and then retrying your action.
我编辑了我的代码,但仍然遇到了这个错误.
jar = cookielib.FileCookieJar("cookies") opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) print len(jar) #prints 0 opener.addheaders = [('User-agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/47.0.2526.111 Safari/537.36')] result = opener.open('https://www.instagram.com') print result.getcode(),len(jar) #prints 200 and 2 url = 'https://www.instagram.com/accounts/login/ajax/' values = {'username' : 'username','password' : 'password'} data = urllib.urlencode(values) response = opener.open(url,data) print response.getcode()
解决方法
>确保你保持合法的一面.根据Instagram的Terms of Use:
We prohibit crawling,scraping,caching or otherwise accessing any content on the Service via automated means,including but not limited to,user profiles and photos (except as may be the result of standard search engine protocols or technologies used by a search engine with Instagram’s express consent).
You must not create accounts with the Service through unauthorized means,by using an automated device,script,bot,spider,crawler or scraper.
>有一个Instagram API将有助于保持合法的一面,让生活更轻松.有一个Python客户端:python-instagram
除此之外,Instagram本身是javascript很重,你可能会发现使用urllib2或请求很难.如果出于某种原因,您无法使用API,则可以通过selenium
查看浏览器自动化.请注意,您也可以自动执行PhantomJS
之类的无头浏览器.以下是登录的示例代码:
from selenium import webdriver USERNAME = "username" PASSWORD = "password" driver = webdriver.PhantomJS() driver.get("https://www.instagram.com") driver.find_element_by_name("username").send_keys(USERNAME) driver.find_element_by_name("password").send_keys(PASSWORD) driver.find_element_by_xpath("//button[. = 'Log in']").click()
Android Java-如何从URL下载zip文件?
嘿,我正在制作一个新项目,要求您从我的DropBox下载一些文件.我添加了一个名为DownloadFile的新类,该类具有下载文件的代码.由于某些原因,当我单击下载时,应用程序崩溃.谢谢.
继承人DownloadFile:
package com.Matt7262.download.app;
import android.support.v7.app.ActionBaractivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.URL;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import android.widget.ProgressBar;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Environment;
import android.view.View.OnClickListener;
public class DownloadFile extends ActionBaractivity{
public void updateProgress(int currentSize, int totalSize)
{
Toast.makeText(getApplicationContext(), "Loading Files...",
Toast.LENGTH_SHORT).show();
}
public void Download()
{
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("https://dl.dropBoxusercontent.com/shz/9cyfz0b45mj6szr/7pBuupNz3N/xecta?token_hash=AAEs9cDFswt98D1IhLnab4dHwhwh5z2Lmhq_N6H-2M0LWg&top_level_offset=6");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"hello.zip");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//Now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we kNow how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
}
主要活动:
package com.Matt7262.download.app;
import android.support.v7.app.ActionBaractivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
public class MainActivity extends ActionBaractivity {
TextView input;
String dpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download";
private DownloadFile df;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//EditText mEdit = (EditText)findViewById(R.id.editText1);
public void buttonOnClick(View v)
{
input = (TextView) findViewById(R.id.editText1);
String dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Ab";
Button button=(Button) v;
//Creating bot
String botname="xecta";
String path= dbPath;
Bot xecta = new Bot(botname, path);
Chat chatSession = new Chat(xecta);
String request = input.getText().toString();
String response = chatSession.multisentenceRespond(request);
((Button) v).setText(response);
}
public void onClickDownload(View view)
{
df.Download();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onoptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onoptionsItemSelected(item);
}
/*public void updateProgress(int currentSize, int totalSize)
{
Toast.makeText(getApplicationContext(), "Retrieving Files...",
Toast.LENGTH_SHORT).show();
}/*
/*public void Download()
{
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("https://dl.dropBoxusercontent.com/shz/9cyfz0b45mj6szr/7pBuupNz3N/xecta?token_hash=AAEs9cDFswt98D1IhLnab4dHwhwh5z2Lmhq_N6H-2M0LWg&top_level_offset=6");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"hello.zip");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//Now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we kNow how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}*/
}
我认为这是我从logcat中获得的所有信息:
logcat
解决方法:
您在声明DownloadFile对象,但未对其进行初始化.
private DownloadFile df;
df.Download(); // Throws NPE
不要忘记初始化它.
private DownloadFile df = new DownloadFile();
df.Download();
编辑:
现在,您初始化了该对象并避免了NPE,但是这次您遇到了networkonmainthreadException.在Honeycomb版本之后,Android不允许您在主线程上进行网络操作.您可以使用AsyncTask来克服此问题.
Python 2.x 中如何使用urllib.quote()函数对URL进行编码
python 2.x 中如何使用 urllib.quote() 函数对 url 进行编码
URL 中包含了多种字符,包括字母、数字、特殊字符等。为了使 URL 能够正确地传输和解析,我们需要对其中的特殊字符进行编码。在 Python 2.x 中,可以使用 urllib.quote() 函数对 URL 进行编码,下面我们来详细介绍其用法。
urllib.quote() 函数属于 urllib 模块,主要用于编码 URL 中的特殊字符。它的基本用法如下:
import urllib encoded_url = urllib.quote(url)
其中,url 是我们要编码的 URL,encoded_url 是编码后的结果。
如果我们需要编码的 URL 中包含了特殊字符,如空格、斜杠、问号等,urllib.quote() 函数会将其替换为 % 加上换码后的 ASCII 码值,以此来保证 URL 的正确性。下面是一个简单的示例:
立即学习“Python免费学习笔记(深入)”;
import urllib url = "https://www.example.com/search?q=python 2.x" encoded_url = urllib.quote(url) print("原始 URL: " + url) print("编码后的 URL: " + encoded_url)
输出结果如下:
原始 URL: https://www.example.com/search?q=python 2.x 编码后的 URL: https://www.example.com/search?q=python%202.x
可以看到,空格被编码为 %20,这样 URL 就可以正常传输和解析了。
需要注意的是,urllib.quote() 函数只会对 URL 中的特殊字符进行编码,对于已经是合法字符的部分,比如字母、数字、点号等,则不会进行处理。所以,在实际使用中,我们只需要对需要的部分进行编码即可,不必担心其他部分的影响。
另外,urllib.quote() 函数还提供了第二个参数,即 safe 参数,用于指定不需要编码的字符。默认情况下,safe 参数是空字符串,表示对 URL 中的所有字符进行编码。如果我们希望某些字符不进行编码,可以将其作为 safe 参数的值传入。例如:
import urllib url = "https://www.example.com/search?q=python 2.x" encoded_url = urllib.quote(url, safe=''/:'') print("编码后的 URL: " + encoded_url)
输出结果如下:
编码后的 URL: https://www.example.com/search?q=python%202.x
可以看到,这次斜杠 / 字符不被编码,而空格仍然被替换为 %20。
总结一下,Python 2.x 中的 urllib.quote() 函数能够帮助我们对 URL 进行编码,以保证其正确传输和解析。通过指定需要编码的 URL 和可选的 safe 参数,我们可以轻松地进行 URL 编码操作。这在实际应用中非常有用,尤其是当我们需要处理一些包含特殊字符的 URL 时。
以上就是Python 2.x 中如何使用urllib.quote()函数对URL进行编码的详细内容,更多请关注php中文网其它相关文章!
Python 2.x 中如何使用urllib2模块发送HTTP请求
引言:
在Python中,我们可以使用urllib2模块来发送HTTP请求。它是Python标准库中的一个模块,可以用于创建请求对象、添加头信息、发送请求,以及处理响应结果等操作。在本文中,我们将详细介绍如何使用urllib2模块发送HTTP请求,并给出相应的代码示例。
- 安装urllib2模块
由于urllib2模块是Python标准库的一部分,所以不需要单独安装。只需要保证Python环境正常,就能使用urllib2模块。 - 发送GET请求
发送GET请求是最常见的HTTP请求方式之一。我们可以使用urllib2.urlopen()函数来发送GET请求,并获取响应结果。
代码示例:
立即学习“Python免费学习笔记(深入)”;
import urllib2 # 发送GET请求 url = ''http://www.example.com'' response = urllib2.urlopen(url) # 获取响应结果 result = response.read() # 输出响应结果 print(result)
在上述代码中,我们首先使用urllib2.urlopen()函数发送了一个GET请求,并将响应结果保存在response变量中。然后,我们使用response.read()方法获取响应结果,并将结果保存在result变量中。最后,我们使用print()函数输出响应结果。
- 发送POST请求
与发送GET请求相比,发送POST请求需要在请求头部中添加一些额外的信息,例如Content-Type和Content-Length。我们可以使用urllib2.Request()函数来创建请求对象,并通过指定data参数来传递POST请求的数据。
代码示例:
立即学习“Python免费学习笔记(深入)”;
import urllib2 import urllib # 发送POST请求 url = ''http://www.example.com'' data = {''key1'': ''value1'', ''key2'': ''value2''} data = urllib.urlencode(data) request = urllib2.Request(url, data=data) response = urllib2.urlopen(request) # 获取响应结果 result = response.read() # 输出响应结果 print(result)
在上述代码中,我们首先定义了一个data字典,其中包含了要传递的POST数据。然后,我们使用urllib.urlencode()函数将数据编码成URL格式。接着,我们使用urllib2.Request()函数创建了一个请求对象,并通过指定data参数来传递POST请求的数据。最后,我们将请求对象传入urllib2.urlopen()函数中发送请求,并通过response.read()方法获取响应结果。
- 自定义请求头信息
有时候,我们需要在发送HTTP请求时添加自定义的请求头信息。我们可以使用urllib2.Request()函数的headers参数来添加自定义的请求头信息。
代码示例:
立即学习“Python免费学习笔记(深入)”;
import urllib2 # 发送带有自定义请求头的GET请求 url = ''http://www.example.com'' headers = {''User-Agent'': ''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3 6''} request = urllib2.Request(url, headers=headers) response = urllib2.urlopen(request) # 获取响应结果 result = response.read() # 输出响应结果 print(result)
在上述代码中,我们定义了一个headers字典,其中包含了自定义的请求头信息。然后,我们通过urllib2.Request()函数的headers参数将自定义的请求头信息添加到请求中。
结语:
通过使用urllib2模块,我们可以方便地发送HTTP请求,并获取响应结果。在本文中,我们通过示例代码详细介绍了GET请求和POST请求的发送方式,以及如何添加自定义的请求头信息。希望这些内容能对你在Python中发送HTTP请求有所帮助。
以上就是Python 2.x 中如何使用urllib2模块发送HTTP请求的详细内容,更多请关注php中文网其它相关文章!
关于如何使用urllib2在python中下载zip文件?和python url下载的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于403禁止使用Urllib2 [Python]、Android Java-如何从URL下载zip文件?、Python 2.x 中如何使用urllib.quote()函数对URL进行编码、Python 2.x 中如何使用urllib2模块发送HTTP请求的相关知识,请在本站寻找。
本文标签: