# This is a learning note for the Liaoche teacher Python tutorial
Compared to Python's built-in urllib module, using requests can be used to better handle URL resources.
1 , using Requests
1) through GET visit a page
>>> Import Requests
>>> r = requests.get(' https://www.douban.com/') # watercress Home
>>> R.Status_code
200
>>> R.text
R.text
' <! DOCTYPE html>\n
2) for parameters with URL , passing in a Dict as a params Parameters:
>>> r = requests.get (' Https://www.douban.com/search ', params={' q ': ' Python ', ' cat ': ' 1001 '})
>>> R.url # The URL we actually requested
'https://www.douban.com/search?q=python&cat=1001'
3) Requests automatically detect the encoding, you can use encoding Properties View
>>> R.Encoding
' Utf-8 '
4) Whether the response is text or binary content, we can use the content Property gets bytes Object
>>> R.Content
B ' <! DOCTYPE html>\n
4) for a specific type of response, such as JSON, you can get directly
>>> r = Requests.get (' https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast% 20where%20woeid%20%3d%202151330&format=json ')
>>> R.JSON ()
{' query ': {' count ': 1, ' created ': ' 2017-11-17t07:14:12z ', ...
5) need to pass in HTTP Header when we pass in a Dict as a Headers Parameters:
>>> r = requests.get (' https://www.douban.com/', headers={' user-agent ': ' mozilla/5.0 (iPhone; CPU iPhone os 11_0 like Mac os X) AppleWebKit '})
>>> R.text
' <! DOCTYPE html>\n
6) to send the POST request, simply turn the Get () method into post () and then pass in the data parameter as the POST request
>>> r = requests. Post (' Https://accounts.douban.com/login ', data={' form_email ': ' [email protected] ', ' form_password ': ' 123456 '})
put post () method is replaced by put () , Delete () and so on, you can request resources in a put or delete way
7) Requests Default Usage application/x-www-form-urlencoded the POST data encoding. If you want to pass JSON data, you can pass in the JSON parameter directly
params = {' key ': ' Value '}
r = requests.post (URL, json=params) # Internally automatically serialized as JSON
8) Uploading a file requires a more complex encoding format, but Requests simplify it to Files Parameters
>>> upload_files = {' file ': Open (' Report.xls ', ' RB ')} # Note Identifiers b , so the length of the file is bytes .
>>> r = requests.post (URL, files=upload_files)
9) Get the response header
>>> R.Headers
{content-type ': ' text/html; Charset=utf-8 ', ' transfer-encoding ': ' chunked ', ' content-encoding ': ' gzip ', ...}
>>> R.headers[' Content-type ']
' Text/html; Charset=utf-8 '
10) Gets the specified Cookies
>>> cs = {' token ': ' 12345 ', ' status ': ' Working '}
>>> r = requests.get (URL, cookies=cs)
11) To specify a time-out, pass in seconds Timeout Parameters
>>> r = requests.get (URL, timeout=2.5) # timeout after 2.5 seconds
Python Learning note __13.2 requests