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()
  • 相关阅读:
    SQL中JOIN 的用法
    ava中普通代码块,构造代码块,静态代码块区别及示例
    javabean的内省技术和BeanUtils的使用
    Tomcat服务器学习和使用(一)
    增强For循环
    JAVA单态设计模式
    关于枚举的整理
    java中遍历MAP的几种方法
    equals和==的区别
    深入剖析Java中的装箱和拆箱
  • 原文地址:https://www.cnblogs.com/ghostwu/p/9124310.html
Copyright © 2011-2022 走看看