python常见库
记录python学习过程,更新ing
1、requests库
1)常见参数:
print(response.status_code) # 打印状态码
print(response.url) # 打印请求url
print(response.headers) # 打印头信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印网页源码
print(response.content) #以字节流形式打印
2)请求方法:
requests.get(‘http://httpbin.org/get’)
requests.post(‘http://httpbin.org/post’)
requests.put(‘http://httpbin.org/put’)
requests.delete(‘http://httpbin.org/delete’)
requests.head(‘http://httpbin.org/get’)
requests.options(‘http://httpbin.org/get’)
3)中文乱码:
方式1:内容编码、打开文件指定编码集
#!/usr/bin/env python
# encoding=utf-8
# -*- coding:utf-8 -*-
import requests
response = requests.get(url='https://www.baidu.com/')
response.encoding='utf-8'
with open('f:/1/1.html','w',encoding='utf-8') as f:
f.write(response.text)
方式2:打开文件指定编码集、写入内容时解码
#!/usr/bin/env python
# encoding=utf-8
# -*- coding:utf-8 -*-
import requests
response = requests.get(url='https://www.baidu.com/')
with open('f:/1/1.html','w',encoding='utf-8') as f:
f.write(response.content.decode('utf-8'))
4)GET请求
heads: 请求头相关内容
params: 当参数过长则及其不方便,此时使用params属性加载参数。自动的将参数按照地址栏的参数形式拼接。以字典形式!
import requests
header = {
'User-Agent': 'aaaa', #自定义请求头,注意末尾逗号
'Cookie': 'security=low; PHPSESSID=u44du355lk47o1s71adis61su2' #加入身份认证信息
}
param = {
p = '内容'
}
url = 'https://www.baidu.com'
response = requests.get(url,headers=header,params=param)
#print(response.text)
5)POST请求
data属性: 接收字典格式数据,与get请求的params相同
header属性: 获取异步请求的数据时,一般加入x-requested-with: XMLHttpRequest
2、time库
当前时间戳: time.time()
获取当前时间: time.localtime()
格式化日期: 2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
3、string
数字0-9: string.digits
小写字母a-z: string.ascii_lowercase:
大写字母A-Z: string.ascii_uppercase:
4、random
指定字符串随机生成n个:random.sample(‘zyxrqponmlkjihgfedcba’,n)
随机1-50整数:random.randint(1,50) #
随机1-101之间,间隔为2的随机整数:random.randrange(1,101,2)