urllib的使用
urllib.request模块
- 版本
python2:urllib2、urllib
python3:把urllib和urllib2合并,urllib.request - 常用方法
- urllib.request.urlopen(“网址”) 作用:向网站发起一个请求并获取响应
- 字节流 = response.read()
- 字符串 = response.read().decode(“utf-8”)
- urllib.request.Request(“网址”,headers=“字典”),urlopen()不支持重构
==urllib.request.urlopen()==的使用
import urllib.request
# response是响应对象
response = urllib.request.urlopen('https://qq.yh31.com/zjbq/2920180.html')
# read()把响应对象里面的内容读取出来
print(response.read())
==urllib/request.Request()==的使用
import urllib.request
url = 'https://www.baidu.com/'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
}
# 1.创建请求对象
req = urllib.request.Request(url,headers=headers)
# 2.获取响应对象
response = urllib.request.urlopen(req)
# 3.读取响应对象内容 (read().decode('utf-8'))
html = response.read().decode('utf-8')
print(html)
# print(response.getcode()) # 返回状态码
# print(response.geturl()) # 返回实际给我们数据的URL
urllib.parse
常用方法
- urlencode(字典)
- quote(字符串)
==urllib.parse.urlencode()==的使用
# https://www.baidu.com/s?wd=%E4%B9%98%E9%A3%8E%E7%A0%B4%E6%B5%AA%E7%9A%84%E5%A7%90%E5%A7%90%E4%BB%AC&ie=utf-8
import urllib.parse
name = {'wd':'乘风破浪的姐姐'}
name = urllib.parse.urlencode(name)
print(name)
==urllib.parse.quote()==的使用
import urllib.parse
baseurl = 'https://www.baidu.com/s?wd='
name = input('请输入搜索内容:')
name = urllib.parse.quote(name)
url = baseurl + name
print(url)