跳到內容

Python 程式設計/網際網路

來自華夏公益教科書


與 Python 捆綁在一起的 urllib 模組可用於 Web 互動。此模組為 Web URL 提供類似檔案的介面。

獲取頁面文字作為字串

[編輯 | 編輯原始碼]

讀取網頁內容的示例

import urllib.request as urllib
pageText = urllib.urlopen("http://www.spam.org/eggs.html").read()
print(pageText)

逐行處理頁面文字

import urllib.request as urllib
for line in urllib.urlopen("https://wikibook.tw/wiki/Python_Programming/Internet"):
  print(line)

也可以使用 Get 和 Post 方法。

import urllib.request as urllib
params = urllib.urlencode({"plato":1, "socrates":10, "sophokles":4, "arkhimedes":11})

# Using GET method
pageText = urllib.urlopen("http://international-philosophy.com/greece?%s" % params).read()
print(pageText)

# Using POST method
pageText = urllib.urlopen("http://international-philosophy.com/greece", params).read()
print(pageText)

下載檔案

[編輯 | 編輯原始碼]

要將網際網路上頁面的內容直接儲存到檔案,您可以將其 read() 並將其作為字串儲存到檔案物件中

import urllib2
data = urllib2.urlopen("http://upload.wikimedia.org/wikibooks/en/9/91/Python_Programming.pdf", "pythonbook.pdf").read() # not recommended as if you are downloading 1gb+ file, will store all data in ram.
file =  open('Python_Programming.pdf','wb')
file.write(data)
file.close()

這將從 這裡 下載檔案,並將其儲存到硬碟上的 "pythonbook.pdf" 檔案中。

其他功能

[編輯 | 編輯原始碼]

urllib 模組包含其他功能,這些功能在編寫使用網際網路的程式時可能會有所幫助

>>> plain_text = "This isn't suitable for putting in a URL"
>>> print(urllib.quote(plain_text))
This%20isn%27t%20suitable%20for%20putting%20in%20a%20URL
>>> print(urllib.quote_plus(plain_text))
This+isn%27t+suitable+for+putting+in+a+URL

上面描述的 urlencode 函式將鍵值對字典轉換為要傳遞給 URL 的查詢字串,quote 和 quote_plus 函式對普通字串進行編碼。quote_plus 函式對空格使用加號,用於提交表單欄位資料。unquote 和 unquote_plus 函式執行相反的操作,將 URL 編碼文字轉換為純文字。

電子郵件

[編輯 | 編輯原始碼]

使用 Python,可以傳送與 MIME 相容的電子郵件。這需要安裝 SMTP 伺服器。

import smtplib
from email.mime.text import MIMEText

msg = MIMEText( 
"""Hi there,

This is a test email message.

Greetings""")

me  = 'sender@example.com'
you = 'receiver@example.com'
msg['Subject'] = 'Hello!'
msg['From'] =  me
msg['To'] =  you
s = smtplib.SMTP()
s.connect()
s.sendmail(me, [you], msg.as_string())
s.quit()

這將從 'sender@example.com' 傳送示例訊息到 'receiver@example.com'。

[編輯 | 編輯原始碼]
華夏公益教科書