get和post以及提交编解码问题
模块:urllib.request ,urllib.parser.urlencode
请求信息:
import urllib.request
ui_headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"}
request=urllib.request.Request('http://www.baidu.com',headers=ui_headers)
response=urllib.request.urlopen(request) #向指定的url放松请求,并返回服务器相应的文件对象
html=response.read()
html=html.decode('utf-8')
print(html)
print(response.getcode())#得到响应状态吗
print(response.geturl())#根据实际数据的实际UEL,防止重定向问题
print(response.info())#返回 服务器响应的HTTP报头
urllib.parse.urlencode()接受的是一个字典
URLlib可以接受url,不能创建设置headers的Request
1 import urllib.request,urllib.parse 2 wd={'wd':'我是一个账号'} 3 id=urllib.parse.urlencode(wd) #通过urllib.parser.urlencode方法,将字典值按url编码转换,从而能被web服务器接受 4 print(id) 5 t=urllib.request.unquote(id) # 通过用urllib.request.unquote方法,吧url编码字符串,转换会原先的字符串 6 print(t) 7 t=urllib.request.unquote(id).encode('utf-8')#r如果返回的是二进制编码 可以用encode进行编码
URLLIB做百度小接口测试
import urllib.request,urllib.parse url=r'http://www.baidu.com/s' keyword=input('请输入需要查询的字符串:') wd={'wd':keyword} wd=urllib.parse.urlencode(wd)#将字符进行编码 fullurl=url+"?"+wd#完整的utl print(fullurl) headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'} request=urllib.request.Request(fullurl,headers=headers)#构造请求对象 response=urllib.request.urlopen(request).read().decode('utf-8') print(response)

浙公网安备 33010602011771号