Python3: urllib.request 的使用

时间:2022-10-08 18:11:38

Python3 的urllib 包含三个部分:

urllib is a package that collects several modules for working with URLs:


下面是我写的一个程序,登录到 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))