10.7. 互联网访问

有许多模块可用于访问互联网和处理互联网协议。其中两个最简单的 urllib.request 用于从URL检索数据,以及 smtplib 用于发送邮件:

  1. >>> from urllib.request import urlopen
  2. >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
  3. ... for line in response:
  4. ... line = line.decode('utf-8') # Decoding the binary data to text.
  5. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time
  6. ... print(line)
  7.  
  8. <BR>Nov. 25, 09:43:32 PM EST
  9.  
  10. >>> import smtplib
  11. >>> server = smtplib.SMTP('localhost')
  12. >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
  13. ... """To: jcaesar@example.org
  14. ... From: soothsayer@example.org
  15. ...
  16. ... Beware the Ides of March.
  17. ... """)
  18. >>> server.quit()

(请注意,第二个示例需要在localhost上运行的邮件服务器。)