python常用库 urllib2介绍 URL编码 发送HTTP请求 读写​csv文件

2015-05-10 21:16:00
admin
原创 3510
摘要:python常用库 urllib2介绍 URL编码 发送HTTP请求 读写​csv文件

一、python常用库

1、http请求库有urllib、urllib2、requests,其中urllib和urlib2是自带模块,推荐使用requests;

2、浏览器自动交互框架selenium,html解析库requests-html,xml解析库lxml,后者更加底层

3、加解密第三方模块包括rsa、pycryptodome、cryptography,推荐使用cryptography;

4、cryptography官方帮助文档:https://cryptography.io/en/latest/


二、urllib和urllib2区别

1、urllib提供urlencode方法编码请求字符串,urllib2没有,urllib和urllib2通常配合使用;

2、urllib2可以接受一个Request实例来设置URL请求头,urllib仅可以接受URL;

3、urllib2支持http、https、ftp;


三、URL编码

1、URL中的保留字符有特殊含义,所以URL上的请求内容需要进行编码,否则URL解释时会出错;

2、URL保留字符:/分割路径,?分割请求内容,=分割name和value,@分割URL用户信息;

3、编码格式是%加上字符的ASCII码;

4、quote编码空格为%20,默认安全字符/,quote_plus编码空格为加号,默认无安全字符;

5、urllib.urlencode调用参数是字典,且使用quote_plus进行编码;

6、编码工具:https://www.bejson.com/enc/urlencode


四、urllib2发送GET请求

1、urlopen自动进行重定向处理;

2、geturl返回重定向后的地址;


def testGet():
    obj = urllib2.urlopen('http://www.3scard.com')
    print obj.geturl()
    print obj.getcode()
    print obj.info()
    print obj.read()


五、urllib2发送POST请求

def testPost(url, data):
    data = urllib.urlencode(data)
    obj = urllib2.urlopen(url, data)
    print obj.read()

def main():
    url = "http://127.0.0.1:8080/springmvc/test_post.do"
    data = {'name':'feinen', 'age':'20'}
    testPost(url , data)


六、urllib2使用opener发送POST请求

def testPost(url, data):
    req = urllib2.Request(url)
    data = urllib.urlencode(data)
    #enable cookie
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    response = opener.open(req, data)
    print response.read()

def main():
    url = "http://127.0.0.1:8080/springmvc/test_post.do"
    data = {'name':'feinen', 'age':'20'}
    testPost(url , data)


七、增加请求头

req.add_header('Content-Type', 'multipart/form-data; boundary=%s; charset=utf-8' % boundary) 
req.add_header('User-Agent','Mozilla/5.0')


八、读写csv文件

构造csv文件对象要以二进制形式打开,即传入参数加b,否则容易产生多余空行。


import csv
if __name__ == '__main__':
    reader = csv.reader(file('aa.csv', 'rb+'))
    writer = csv.writer(file('bb.csv', 'wb+'))
    for line in reader:
        print reader.line_num
        print line
        writer.writerow(line)

发表评论
评论通过审核之后才会显示。