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. <BR>Nov. 25, 09:43:32 PM EST
  8. >>> import smtplib
  9. >>> server = smtplib.SMTP('localhost')
  10. >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
  11. ... """To: jcaesar@example.org
  12. ... From: soothsayer@example.org
  13. ...
  14. ... Beware the Ides of March.
  15. ... """)
  16. >>> server.quit()

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