urllib中的get使用,以访问智联为例

python3中的urllib库的get使用,以访问智联为例,虽然现在智联需要验证码了,但是也不妨我们做个练习,巩固下get的使用。

#如果一个网站屏蔽了你
#解决办法: (1)模拟浏览器  ; (2)伪装浏览器
import urllib
import urllib.request
from urllib import parse
def download1(addr,mytype):
    url="https://sou.zhaopin.com/?"
    headers={"User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"}  #header 字典形式
    #选择代码  ctrl + 鼠标左键 查看变量或者函数或者类的定义

    word={"jl":addr,"kw":mytype}    #接口
    word=parse.urlencode(word)  #编码成字符串
    url=url+word     #拼接url


    request=urllib.request.Request(url,headers=headers)   # 发送请求
    #也可以通过调用Request.add_header()  添加/修改一个特定的  header
    request.add_header("Connection","keep-alive")  #一直活着
    response=urllib.request.urlopen(request)  #打开请求
    data=response.read()    #读取数据
    print(response.code)    #可以查看相应状态码
    return data


addr="上海"  #urlopen只能处理http,不可以处理https
mytype="python"
print(download1(addr,mytype).decode("utf-8"))    #decode("utf-8")  二进制解码为utf-8
原文地址:https://www.cnblogs.com/my-global/p/12441150.html