Detailed explanation of how to use Python's Requests module
The Requests module is a module used for network access. In fact, there are many similar modules, such as urllib, urllib2, httplib, httplib2. They basically provide similar functions, so why can the Requests module stand out? You can open its official website and take a look. It is an http module for "human beings". So, how human is it? I believe that if you have used modules such as urllib before, you will find that it is indeed very user-friendly.
1. Import
After the download is completed, importing the module is very simple. The code is as follows:
import requests
2. Request URL
Here we list the most common The syntax for sending get or post requests.
1. Send a get request without parameters:
r=requests.get("http://php.cn/justTest")
Now, we get a response object r, we can use this object to get any information we want.
In the above example, the get request does not have any parameters. What if the request requires parameters?
2. Send a get request with parameters
payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://php.cn/justTest", params=payload)
As we know from the above, our get parameters are passed as params keyword parameters.
We can print the specific URL requested to see if it is correct:
>>>print r.url http://pythontab.com/justTest?key2=value2&key1=value1
You can see that the correct URL was indeed accessed.
You can also pass a list to a request parameter:
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']} >>> r = requests.get("http://php.cn/justTest", params=payload) >>> print r.url http://pythontab.com/justTest?key1=value1&key2=value2&key2=value3
The above is the basic form of the get request.
3. Send a post request
r = requests.post("http://php.cn/postTest", data = {"key":"value"})
As we know from the above, the post request parameters are passed as data keyword parameters.
The current data parameter passes a dictionary, we can also pass a json format data, as follows:
>>> import json >>> import requests >>> payload = {"key":"value"} >>> r = requests.post("http://php.cn/postTest", data = json.dumps(payload))
Since sending json format data is too common, in the higher version of the Requests module , the keyword parameter json has been added. You can directly send json data to the post request without using the json module. See below:
>>> payload = {"key":"value"} >>> r = requests.post("http://php.cn/postTest", json=payload)
What if we want to post a file? At this time, you need to use the files parameter:
>>> url = 'http://php.cn/postTest' >>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files) >>> r.text
We can also specify additional information such as the file name when posting the file:
>>> url = 'http://php.cn/postTest' >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} >>> r = requests.post(url, files=files)
tips: It is strongly recommended to use binary mode to open the file, because If opened in text file format, an error may occur due to the "Content-Length" header.
As you can see, it is easy to send requests using Requests!
3. Obtain the return information
Let’s take a look at how to obtain the return information after sending the request. Let’s continue to use the top example: In what encoding format is
>>> import requests >>> r=requests.get('http://php.cn/justTest') >>> r.text
r.text output?
>>> r.encoding 'utf-8'
It turned out to be output in utf-8 format. What if I want to change the output format of r.text?
>>> r.encoding = 'ISO-8859-1'
This changes the output format to "ISO-8859-1".
There is also an output statement called r.content, so what is the difference between this and r.text? r.content returns a byte stream, which can be used if we request an image address and want to save the image. Here is a code snippet as follows:
def saveImage( imgUrl,imgName ="default.jpg" ): r = requests.get(imgUrl, stream=True) image = r.content destDir="D:\" print("保存图片"+destDir+imgName+"\n") try: with open(destDir+imgName ,"wb") as jpg: jpg.write(image) return except IOError: print("IO Error") return finally: jpg.close
The r.text just introduced returns String, then, if the response corresponding to the request is a json, can I directly get the data in json format? r.json() is prepared for this.
We can also get the original data returned by the server, just use r.raw.read(). However, if you really want to get the original return data, remember to add the "stream=True" option when requesting, such as:
r = requests.get('https://api.github.com/events', stream=True)。
We can also get the response status code:
>>> r = requests.get('http://php.cn/justTest') >>> r.status_code 200
You can also use requests.codes.ok to refer to the return value of 200:
>>> r.status_code == requests.codes.ok True
4. About headers
We can print out the response header:
>>> r= requests.get("http://php.cn/justTest") >>> r.headers
`r .headers` returns a dictionary, for example:
{ 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'connection': 'close', 'server': 'nginx/1.0.4', 'x-runtime': '147ms', 'etag': '"e1ca502697e5c9317743dc078f67693a"', 'content-type': 'application/json' }
We can use the following method to obtain part of the response headers for judgment:
r.headers['Content-Type']
or
r.headers.get('Content-Type')
If we want What should we do to get the request header (that is, the header information we send to the server)? Can be obtained directly using r.request.headers.
At the same time, we can also add custom headers (passed through headers keyword parameters) when requesting data:
>>> headers = {'user-agent': 'myagent'} >>> r= requests.get("http://php.cn/justTest",headers=headers)
5. About Cookies
If a response If cookies are included, we can use the following method to get them:
>>> url = 'http://www.php.cn' >>> r = requests.get(url) >>> r.cookies['example_cookie_name'] 'example_cookie_value'
We can also send our own cookies (using the cookies keyword parameters):
>>> url = 'http://php.cn/cookies' >>> cookies={'cookies_are':'working'} >>> r = requests.get(url, cookies=cookies)
6. About redirection
Sometimes when we request the URL, the server will automatically redirect our request. For example, github will redirect our http request to https request. We can use r.history to view redirects:
>>> r = requests.get('http://php.cn/') >>> r.url 'http://php.cn/' >>> r.history []
As you can see from the above example, we use the http protocol to access, but in r.url, the https protocol is printed. So what should I do if I insist that the server use the http protocol, which means that the server is prohibited from automatically redirecting? Use the allow_redirects parameter:
r = requests.get('http://php.cn', allow_redirects=False)
7. About the request time
We can use the timeout parameter to set the request timeout of the url (time unit is seconds):
requests.get('http://php.cn', timeout=1)
8 , About proxy
We can also specify a proxy in the program for http or https access (using proxies keyword parameters), as follows:
proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://php.cn", proxies=proxies)
九、关于session
我们有时候会有这样的情况,我们需要登录某个网站,然后才能请求相关url,这时就可以用到session了,我们可以先使用网站的登录api进行登录,然后得到session,最后就可以用这个session来请求其他url了:
s=requests.Session() login_data={'form_email':'youremail@example.com','form_password':'yourpassword'} s.post("http://pythontab.com/testLogin",login_data) r = s.get('http://pythontab.com/notification/') print r.text
其中,form_email和form_password是豆瓣登录框的相应元素的name值。
十、下载页面
使用Requests模块也可以下载网页,代码如下:
r=requests.get("http://www.php.cn") with open("haha.html","wb") as html: html.write(r.content) html.close()
The above is the detailed content of Detailed explanation of how to use Python's Requests module. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment