Python爬虫学习笔记
写在最前
Python爬虫学习笔记
urllib的使用
urllib是python内置的对URL进行处理的库,包含四个基本的模块:
urllib.request用来对url发送请求
urllib.parse用来解析url
urllib.error用来判断request发送的返回值
urllib.robotsparser用来解析robots.txt
urllib.request的用法
可以使用下列语句访问url:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
若不加data,则访问方法为get请求方法,加上data为post请求方法
get与post的区别如下:
GET - 从指定的资源请求数据。
POST - 向指定的资源提交要被处理的数据
requests库的应用
在调用requests库时,直接输入
import requests
-
requests库支持使用多个请求方式访问网站,可以直接使用get或post方式。该方式返回一个response对象。
-
requests库可以使用params关键字传递一个字典的参数,构造url。
-
requests库可以使用headers关键字添加访问者的用户信息。
-
post方法中可以添加一个data参数,data参数由字典组成,作为post请求中向html发送的要处理的数据。
-
get或post方法中可添加timeout参数设置访问时间上限。
-
get或post方法中可添加proxies参数添加proxy,proxies参数格式如下:
proxies= {
"http":"http://user:password@127.0.0.1:9999",
"https":"http://127.0.0.1:8888"
}
- get或post方法中可通过添加auth参数设置认证,也可以通过requests.auth模块实现:
response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
import requests
from requests.auth import HTTPBasicAuth
response = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
print(response.status_code)
-
requests.json()可以将requests返回的对象转化为dict类。
-
request.Session()可以实现访问多次访问网站时cookie保持不变
通过response可以获取到许多属性,例如:
import requests
response = requests.get("https://www.baidu.com")
print(type(response.status_code),response.status_code)
print(type(response.headers),response.headers)
print(type(response.cookies),response.cookies)
print(type(response.url),response.url)
print(type(response.history),response.history)
待更新