python2.7和3.5的http請求(urllib, urllib等)
阿新 • • 發佈:2019-02-16
需求的請求格式: http://www.baidu.com/s?wd=word&time=time
python2.7
python3.5# !/usr/bin/python # -*- coding:utf-8 -*- import urllib2 import urllib def sendReq(): url = 'http://www.baidu.com/s' values = {'wd':'word','time':'time'} params = urllib.urlencode(values) req = urllib2.Request(url + '?' + params) response = urllib2.urlopen(req) print response.read()
# !/usr/bin/python
# -*- coding:utf-8 -*-
import urllib.request
import urllib.parse
def sendReq():
params = urllib.parse.urlencode({'wd':'word','time':'time'})
url = 'http://www.baidu.com/s?%s' % params
with urllib.request.urlopen(url) as f:
print f.read().decode('utf-8')