zoukankan      html  css  js  c++  java
  • 【6】Python网络请求:urllib模块

    python操作网络,也就是打开一个网站,或者请求一个http接口,可以使用urllib模块。
    urllib模块是一个标准模块,直接import urllib即可,在python3里面只有urllib模块,在python2里面有urllib模块和urllib2模块

    Urllib是python内置的HTTP请求库
    包括以下模块
    urllib.request 请求模块
    urllib.error 异常处理模块
    urllib.parse url解析模块
    urllib.robotparser robots.txt解析模块

    因为有更好用的模块,所以再在此不对此模块进行更多解释,想更好的学习urllib模块可以参考下面的博客或官方文档。

    参考博客:http://www.cnblogs.com/zhaof/p/6910871.html

    官方文档:https://docs.python.org/3/library/urllib.html

    import json
    from urllib.request import urlopen # 打开网页
    from urllib.parse import urlencode
    
    # ====get请求====
    url='https://www.cnblogs.com/haifeima/p/9829601.html#autoid-5-0-5'
    res=urlopen(url).read()#发起get请求,并获取结果
    print(res.decode())#返回的是二进制类型,所以要decode变成字符串
    f=open('b.html','w',encoding='utf-8') #将上面的网页保存到本地,执行后会在本地生成一个叫做b.html的文件
    f.write(res.decode())
    f.close()
    
    
    # ====post请求====
    url='http://api.nnzhp.cn/api/user/login'
    data={"username":"niuhanyang","passws":"aA123456"}
    data=urlencode(data)
    res=urlopen(url,data).read()#发起post请求,加个date把数据传进来,获取结果
    print(res.decode())#转成decode格式
    d=json.loads(res.decode())#转成字典
    print(d.get('login_info').get('sign'))
    f=open('b.html','w',encoding='utf-8') #将上面的网页保存到本地,执行后会在本地生成一个叫做b.html的文件
    f.write(res.decode())
    f.close()
  • 相关阅读:
    idea Ctrl+Alt+向下箭头 复制不起作用问题解决
    @Data 注解使用
    idea class类增加注释
    mysql 固定用户赋值数据库权限
    springboot logback 详细配置
    gitblit 增加ssh key
    uniapp内嵌H5页面和uniapp页面相互传值
    博客搬家
    反编译,java字节流 ,wirshark抓包,php转换中文
    charles 双向抓包
  • 原文地址:https://www.cnblogs.com/haifeima/p/9928354.html
Copyright © 2011-2022 走看看