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()

猜你喜欢

转载自www.cnblogs.com/ghostwu/p/9124310.html