python爬虫入门urllib库的使用
2018-06-18 03:16:05来源:未知 阅读 ()
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()
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
