Python3 的urllib 包含三个部分:
urllib
is a package that collects several modules for working with URLs:
-
urllib.request
for opening and reading URLs -
urllib.error
containing the exceptions raised byurllib.request
-
urllib.parse
for parsing URLs -
urllib.robotparser
for parsingrobots.txt
files
下面是我写的一个程序,登录到 pytonprogramming.net ,search 内容为basic, 然后把结果记录在一个txt 里面。
#/usr/bin/python #post import urllib.request import urllib.parse try: url = 'http://pythonprogramming.net' values = {'s':'basic', 'submit':'search'} data = urllib.parse.urlencode(values) data = data.encode('utf-8') print(data) req = urllib.request.Request(url,data) response = urllib.request.urlopen(req) respData = response.read() print(respData) saveFile = open('withoutheader.txt','w') saveFile.write(str(respData)) saveFile.close() except Exception as e: print(str(e))