Python-urllib2下载网页

方法一

import urllib2
#直接下载
url = "http://www.baidu.com"
response = urllib2.urlopen(url)
#获取状态码, 200表示成功
if response.getcode() == 200:
    #读取内容
    content = response.read()
    print content;

方法二

import urllib2
url = "http://www.baidu.com"
request = urllib2.Request(url)
request.add_header("user-agent", "Mozilla/5.0")
response1 = urllib2.urlopen(request)
if response1.getcode() == 200:
    print response1.read()

方法三

import urllib2
import cookielib
url = "http://www.baidu.com"
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
response3 = urllib2.urlopen(url)
if response3.getcode() == 200:
    print response3.read()
    print cj

你可能感兴趣的:(Python-urllib2下载网页)