1. 程式人生 > >python2.7和3.5的http請求(urllib, urllib等)

python2.7和3.5的http請求(urllib, urllib等)

需求的請求格式: http://www.baidu.com/s?wd=word&time=time

python2.7

# !/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()
python3.5
# !/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')