• urllib使用一


    urllib.urlopen()方法:

    参数:

    1.url(要访问的网页链接http:或者是本地文件file:)

    2.data(如果有,就会由GET方法变为POST方法,提交的数据格式必须是application/x-www-form-urlencoded格式)

    返回值:

    返回类文件句柄

    常用方法

    read(size)--size=-1/None,读取多少字节数据取决于size的值,负数就是读取全部内容,默认省略size然后读取全部

    readline()读取一行

    readlines()读取所有行,返回列表

    close()

    getcode()返回http请求应答码

    urllib基本使用:

    一、打印输出100字节

    import urllib
    
    html = urllib.urlopen("http://www.runoob.com/python/python-email.html")
    print(html.read(100))

    打印结果:

    <!Doctype html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    如果不设定read(size)size参数,就会全部读取

    二、readline()

    import urllib
    
    html = urllib.urlopen("http://www.runoob.com/python/python-email.html")
    print(html.readline())

    读取一行内容出来

    运行结果:

    <!Doctype html>

    for循环遍历几行出来

    import urllib
    
    html = urllib.urlopen("http://www.runoob.com/python/python-email.html")
    for i in range(10):
        
        print("line %d: %s"%(i+1,html.readline()))

    运行结果:

    line 1: <!Doctype html>
    
    line 2: <html>
    
    line 3: <head>
    
    line 4: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    
    line 5: <meta property="qc:admins" content="465267610762567726375" />
    
    line 6: <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
    line 7: <title>Python SMTP发送邮件 | 菜鸟教程</title>
    
    line 8: <link rel='dns-prefetch' href='//s.w.org' />
    
    line 9: <link rel="canonical" href="http://www.runoob.com/python/python-email.html" />
    
    line 10: <meta name="keywords" content="Python SMTP发送邮件">

    三、readlines()方法

    import urllib
    
    html = urllib.urlopen("http://www.runoob.com/python/python-email.html")
    print(html.readlines())

    四、getcode()方法

    import urllib
    
    html = urllib.urlopen("http://www.runoob.com/python/python-email.html")
    print(html.getcode())

    返回200 OK状态码

     定义打印列表方法,后面会用到

    def print_list(lists):
        for i in lists:
            print(i)
  • 相关阅读:
    JavaScript控制改变鼠标的形状
    web控件开发系列(四) 自定义控件属性(上)
    web控件开发系列() 基础介绍
    Web前端面试题 Js把URL中的参数解析为一个对象
    节点的操作 创建、添加、移除、移动、复制
    一个sohoto广告弹出页提取时间的Js修改过程
    FireFox支持innerText的方法
    Js 基于html5localStorage方法 制作的 "我的便签本"
    原生JavaScript对CSS进行格式化和压缩
    JavaScript 命名规则 变量命名规则
  • 原文地址:https://www.cnblogs.com/chillytao-suiyuan/p/9147589.html
Copyright © 2020-2023  润新知