1 版本
python2 : urllib urllib2
python3 : 把urllib 和 urllib2合并,urllib.request
2 常用方法
2.1urllib.request.urlopen("网址") 向网站发起一个请求并获取响应
2.1.1字节流 = response.read()
字符串 = response.read().decode("utf-8")31
encode() : 字符串--->bytes
decode(): bytes-->字符串
2.2 重构User-Agent
2.2.1 不支持重构User-Agent :urlopen()
2.2.2 支持重构 User-Agent :urllib.request.Request("网址",headers="字典")
User-Agent 是爬虫和反爬虫斗争的第一步,发送请求必须带User-Agent
2.2.2.1 使用流程
2.2.2.1.1 利用Request方法构建请求对象
2.2.2.1.2 利用urlopen()获取响应对象
2.2.2.1.3 利用响应对象的read().decode("utf-8") 获取内容
2.2.2.2 响应对象 response的方法
2.2.2.2.1 read() 读取服务器响应的内容
2.2.2.2.2 getcode()
作用 返回HTTP响应码 print(response.getcode())
200 成功
4xx 服务器页面出错 5xx 服务器出错
2.2.2.2.3 geturl()
作用 返回实际数据的url (防止重定向问题)
3 urllib.parse 模块
3.1 urlencode(字典)
urlencode({"wd":"美女"}) wd=%e%rr.......
3.2 quote(字符串)
aseurl = "http://www.baidu.com/s?wd="
key = input("请输入要搜索的内容:")
#用quote()编码
key = urllib.parse.quote(key)
url = baseurl + key
print(url)
发请求 - 响应(html源码)- 解析