留下快樂和驚喜 與過去近一點

星期三, 9月 30, 2015

Python 3.5.0 urllib 用法

在網上搜索使用Python語言的網絡爬蟲(Crawler)程式碼時,經常會出現導入(import) "urllib" 及 "urllib2" 模組(module)的程式碼。

但是在 Python 3.X 的版本中,將 "urllib" 和 "urllib2" 模組合併為 "urllib" 下的模組,分別是"urllib.error","urllib.request","urllib.response",還有 "urllib.parse" 及 "urllib.robotparser" 。

不過要留意導入 "urllib" 是不會同時導入 urllib 下的模組。
以下會用 Python 內建函數(Built-in Function)中的 "dir()" 作示範。
# Print every function inside a module
import urllib               # Imports the urllib module
print (dir(urllib))         # Prints urllib

# Print every function inside a module
import urllib.error         # Imports the urllib.error module
print (dir(urllib.error))   # Prints urllib.error

# Print every function inside a module
import urllib.request       # Imports the urllib.request module
print (dir(urllib.request)) # Prints urllib.request

如要導入模組,需要指明模組的名稱,如下
import urllib.request
import urllib.response
import urllib.error
在 Python 3.X 中,以下左方的語法要 改成 右方的語法
urllib2.urlopen() 改成 urllib.request.urlopen()
urllib2.Request() 改成 urllib.request.Request()

想了解更多,可參考以下英文教學。
Python 3.X Porting Guide

0 意見:

發佈留言

Copyright © Matt Ko in UK 旅英紀錄 | Powered by Blogger

Design by Matthew Ko | Blogger Theme by NewBloggerThemes.com