import urllib.request
import urllib.parse
import string
def get_params():
url = "http://www.baidu.com/s?w"
params = {
"wd": "中文",
"key":"zhang",
"value":"san"
}
#urlencode 可以将字典直接拼接到原来的url
new_url = urllib.parse.urlencode(params)
print(new_url)
end_url = url + new_url
print(end_url)
response = urllib.request.urlopen(end_url)
print(response)
html = response.read()
print(html)
get_params()
urlopen(url, data, tiemout)
data 是post请求的
1.get传参
汉字报错:解释器不能识别,url汉字转码
urllib.parse.quote safe="string.printtable"
字典传参:
urllib.parse.urlencode()
2.post:
urllib.request.openurl(url,data="<服务器接收的数据>")
data是post请求下的
#handler:处理器的自定义
Request(url, data, headers={})
添加请求头信息
urllib.request.Request(url, headers={ ... })
动态添加UA
request.add_header("User-Agent", "<UA>")
返回ua信息
request.get_headers("User-agent")
获取完成的URL
final_url = request.get_full_url()
User-Agent 模拟真实的浏览器发送请求
###ip代理
ip分类:
透明:对方知道我们的真实ip
匿名:对方不知道我们的真实ip,知道你使用了代理
高匿:对方不知道我们真实ip,也不知道我们使用了代理
###handler
系统的urlopen没有添加代理的功能,需要我们自定义这个功能
安全 套接层 ssl第三方的ca数字证书
https443端口 和 http80端口
urlopen为啥可以请求数据
handler处理器 和自己的oppener请求数据
url = "***"
#创建自己的处理器
handler = urllib.request.HTTPHandler()
#创建自己的opener
opener = urllib.request.build_opener(handler)
#用自己创建的opener调用open方法
response = opener.open(url)
###proxy-handler 添加代理
url = " *** "
添加代理
proxy = {
#免费的写法
#官方写法
"http":"http://120.77.249.45:8080"
#简写
"http":"120.77.249.45:8080"
#付费写法
"http":"username:pwd@120.77.249.45:8080"
}
#代理处理器
proxy_handler = urllib.request.ProxyHandler(proxy)
#创建opener
opener = urllib.request.build_opener(proxy_handler)
#拿着代理ip发送请求
data = opener.open(url).read()
handler:
系统的urlopen不支持代理的添加
创建对应的处理器,handler
1.代理的处理器:ProxyHandler
2.拿着ProxyHandler创建opener:bulid_opener()
3.拿着opener.open(url)请求数据
#创建ip代理池
proxy_list =[
{"http":"120.12.16.16:8080"},
{"http":"***.**.**.**:****"},
{"http":"***.**.**.**:****"},
{"http":"***.**.**.**:****"},
]
for proxy in proxy_list:
# 利用遍历出来的ip创建处理器
#代理处理器
proxy_handler = urllib.request.ProxyHandler(proxy)
#创建opener
opener = urllib.request.build_opener(proxy_handler)
try:
#拿着代理ip发送请求
data = opener.open(<url>,timeout=1)
except Exception as e:
print(e)
auth认证handler
Cookiehandler
URLError
requests(第三方模块) :简单易用
数据解析:
数据存储:json csv MongDB resdis mysql