python3.x中的urllib子產品
最新版的python3.3.0已經釋出了。相較于python3.0,3.2的改動并不大。但網上的大量的教程等大都以2.x版本為基礎。這為想要從python3.0學起的菜鳥帶來了不少的困難。
作為一隻菜鳥,最近想學習一下python中urllib子產品的使用方法。從網上找的最簡單的執行個體:把google 首頁的html抓取下來并顯示在控制台上
代碼:
import urllib
print urllib.urlopen('http://www.google.com').read()
首先,使用過python3.0的朋友都知道,print已經變成含樹了,需要括号。但這不是主要問題。問題是控制台顯示錯誤,說urllib子產品中沒有urlopen方法。
奇怪了,網上的教程能錯了?又嘗試help(urllib),發現什麼方法都沒有,隻提供了package contents,裡面有5個名字。
作為一名新手,第一感覺是十分慌亂,是不是IDLE壞了,重裝試試。。。當然所有嘗試都以失敗告終。
最後,我嘗試着找找python3.3.0的change log。裡面并沒有找到urllib的修改記錄。然而這一修改記錄卻在python3.0的change log中。
原文是這樣寫的:
a new urllib package was created. It consists of code from
urllib, urllib2, urlparse, and robotparser. The old
modules have all been removed. The new package has five submodules:
urllib.parse, urllib.request, urllib.response,
urllib.error, and urllib.robotparser. The
urllib.request.urlopen() function uses the url opener from
urllib2. (Note that the unittests have not been renamed for the
beta, but they will be renamed in the future.)
原來,3.0版本中已經将urllib2、urlparse、和robotparser并入了urllib中,并且修改urllib子產品,其中包含5個子子產品,即是help()中看到的那五個名字。
為了今後使用友善,在此将每個包中包含的方法列舉如下:
urllib.error: ContentTooShortError; HTTPError; URLError
urllib.parse: parse_qs; parse_qsl; quote; quote_from_bytes; quote_plus; unquote
unquote_plus; unquote_to_bytes; urldefrag; urlencode; urljoin; urlparse;
urlsplit; urlunparse; urlunsplit
urllib.request: AbstractBasicAuthHandler; AbstractDigestAuthHandler; BaseHandler;
CatheFTPHandler; FTPHandler; FancyURLopener; FileHandler;
HTTPBasicAuthHandler; HTTPCookieProcessor; HTTPDefaultErrorHandler;
HTTPDigestAuthHandler; HTTPErrorProcessorl; HTTPHandler;
HTTPPasswordMgr; HTTPPasswordMgrWithDefaultRealm;
HTTPRedirectHandler; HTTPSHandler;OpenerDirector;ProxyBasicAuthHandler
ProxyDigestAuthHandler; ProxyHandler; Request; URLopener;
UnknowHandler; build_opener; getproxies; install_opener; pathname2url;
url2pathname; urlcleanup; urlopen; urlretrieve;
urllib.response: addbase; addclosehook; addinfo; addinfourl;
urllib.robotparser: RobotFileParser
當然,python3.0的改動十分巨大,有需要可以參閱change log
如果想要學習python的話,還是建議從3.0起步。因為畢竟時代是發展的,追随最新的東西至少不是錯的。