zoukankan      html  css  js  c++  java
  • python爬虫入门urllib库的使用

    urllib库的使用,非常简单。

    import urllib2
    
    response = urllib2.urlopen("http://www.baidu.com")
    print response.read()

    只要几句代码就可以把一个网站的源代码下载下来。

    官方文档:https://docs.python.org/2/library/urllib2.html

    urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

    urlopen 只要用到前面3个参数,url, data:提交的数据. timeout:超时

    也可以这样使用:

    import urllib2
    
    request = urllib2.Request("http://www.baidu.com")
    response = urllib2.urlopen(request)
    print response.read()

    这种用法比较常见。

     我们用php创建一个表单,然后用urllib2模拟表单提交

    <!doctype html>
    <html>
        <head>
            <meta charset="utf-8" />
        </head>
        <body>
            <?php
                if( isset( $_REQUEST['submit'] ) ) {
                    $username = $_REQUEST['username'];
                    $userpwd = $_REQUEST['password'];
                    if( $username == 'ghostwu' && $userpwd = 'abc123') {
        echo "login success";
    }else{
        echo "login error";
    }
                }
            ?>
            <form action="/index.php" method="get">
                username: <input type="text" name="username" /><br/>
                password: <input type="password" name="password" /><br/>
                <input type="submit" value="submit" name="submit" />
            </form>
        </body>
    </html>

    接下来,我们先用get方式提交【备注:域名是我本地的,你需要用本地host映射,相应的服务器域名和ip】

    #coding:utf-8
    
    import urllib
    import urllib2
    
    values = { "username" : "ghostwu", "password" : "abc123", "submit" : "submit" }
    data = urllib.urlencode( values )
    url = "http://mesite.ghostwu" + "?" + data
    request = urllib2.Request( url )
    response = urllib2.urlopen( request )
    print response.read()

    执行之后,如果把用户名或者密码该错,就会出现login error.

    post提交方式,当然你要把php表单改成post提交.

    #!/usr/bin/python
    #coding:utf-8
    
    import urllib
    import urllib2
    
    values = { "username" : "ghostwu2", "password" : "abc123", "submit" : "submit" }
    data = urllib.urlencode( values )
    url = "http://mesite.ghostwu"
    request = urllib2.Request( url, data )
    response = urllib2.urlopen( request )
    print response.read()
  • 相关阅读:
    读邮件正文
    收邮件
    算法 字符串转换为以为数组
    获取下拉框的值
    thinphp 模版标签中 除了volist 和 if 其余的标签中的变量不需要$符号
    php 时间戳处理 自定义时间戳
    jquery 根据json 生成数据 根据生成的数据选择对应的
    php qrcode 二维码 扫描后多行在软件中输出问题
    数组转换为字符串
    浏览器的同源策略
  • 原文地址:https://www.cnblogs.com/ghostwu/p/9124310.html
Copyright © 2011-2022 走看看