import urllib2 enable_proxy = True proxy_handler = urllib2.ProxyHandler({"http" : ‘http://some-proxy.com:8080‘}) null_proxy_handler = urllib2.ProxyHandler({}) if enable_proxy: opener = urllib2.build_opener(proxy_handler) else: opener = urllib2.build_opener(null_proxy_handler) urllib2.install_opener(opener)
import urllib2 import socket socket.setdefaulttimeout(10) # 10 秒钟后超时 urllib2.socket.setdefaulttimeout(10) # 另一种方式
import urllib2 response = urllib2.urlopen(‘http://www.google.com‘, timeout=10)
import urllib2 request = urllib2.Request(‘http://www.baidu.com/‘) request.add_header(‘User-Agent‘, ‘fake-client‘) response = urllib2.urlopen(request) print response.read()
import urllib2 my_url = ‘http://www.google.cn‘ response = urllib2.urlopen(my_url) redirected = response.geturl() == my_url print redirected my_url = ‘http://rrurl.cn/b1UZuP‘ response = urllib2.urlopen(my_url) redirected = response.geturl() == my_url print redirected
import urllib2 class RedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): print "301" pass def http_error_302(self, req, fp, code, msg, headers): print "303" pass opener = urllib2.build_opener(RedirectHandler) opener.open(‘http://rrurl.cn/b1UZuP‘)
import urllib2 import cookielib cookie = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) response = opener.open(‘http://www.baidu.com‘) for item in cookie: print ‘Name = ‘+item.name print ‘Value = ‘+item.value
import urllib2 request = urllib2.Request(uri, data=data) request.get_method = lambda: ‘PUT‘ # or ‘DELETE‘ response = urllib2.urlopen(request)
import urllib2 try: response = urllib2.urlopen(‘http://bbs.csdn.net/why‘) except urllib2.HTTPError, e: print e.code
import urllib2 httpHandler = urllib2.HTTPHandler(debuglevel=1) httpsHandler = urllib2.HTTPSHandler(debuglevel=1) opener = urllib2.build_opener(httpHandler, httpsHandler) urllib2.install_opener(opener) response = urllib2.urlopen(‘http://www.google.com‘)
# -*- coding: utf-8 -*- import urllib import urllib2 postdata=urllib.urlencode({ ‘username‘:‘汪小光‘, ‘password‘:‘why888‘, ‘continueURI‘:‘http://www.verycd.com/‘, ‘fk‘:‘‘, ‘login_submit‘:‘登录‘ }) req = urllib2.Request( url = ‘http://secure.verycd.com/signin‘, data = postdata ) result = urllib2.urlopen(req) print result.read()
#… headers = { ‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘ } req = urllib2.Request( url = ‘http://secure.verycd.com/signin/*/http://www.verycd.com/‘, data = postdata, headers = headers ) #...
参考来源:
零基础写python爬虫之urllib2使用指南
http://www.lai18.com/content/384669.html
2零基础写python爬虫之使用urllib2组件抓取网页内容
4零基础写python爬虫之urllib2中的两个重要概念:Openers和Handlers
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u011252402/article/details/47310801