Python設置Headers
import urllib import urllib2 url = 'http://www.server.com/login' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {'username' : 'cqc', 'password' : 'XXXX' } headers = { 'User-Agent' : user_agent } data = urllib.urlencode(values) request = urllib2.Request(url, data, headers) response = urllib2.urlopen(request) page = response.read()
這樣,我們設置了一個headers,在構建request時傳入,在請求時,就加入了headers傳送,服務器若識別了是瀏覽器發來的請求,就會得到響應。
另外,我們還有對付”反盜鏈”的方式,對付防盜鏈,服務器會識別headers中的referer是不是它自己,如果不是,有的服務器不會響應,所以我們還可以在headers中加入referer
例如我們可以構建下面的headers
headers = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', 'Referer': 'http://www.zhihu.com/articles' }
另外headers的一些屬性,下面的需要特別注意一下:
- User-Agent : 有些服務器或 Proxy 會通過該值來判斷是否是瀏覽器發出的請求
- Content-Type : 在使用 REST 接口時,服務器會檢查該值,用來確定 HTTP Body 中的內容該怎樣解析。
- application/xml : 在 XML RPC,如 RESTful/SOAP 調用時使用
- application/json : 在 JSON RPC 調用時使用
- application/x-www-form-urlencoded : 瀏覽器提交 Web 表單時使用
- 在使用服務器提供的 RESTful 或 SOAP 服務時, Content-Type 設置錯誤會導致服務器拒絕服務
異常拋出
import urllib import urllib2 url = 'http://www.server.com/login' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {'username' : 'cqc', 'password' : 'XXXX' } headers = { 'User-Agent' : user_agent } data = urllib.urlencode(values) request = urllib2.Request(url, data, headers) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: print e.code print e.reason page = response.read()