title: Python 技巧整理
copyright: true
top: 0
date: 2018-06-16 18:29:40
tags: Python技巧
categories: Python基础笔记
permalink:
password:
keywords: Python技巧
description: Python在开发的时候常用的小技巧
编码加密类
hex编码
使用hex(‘a’)是不行的,如果想要对字符串hex编码可以这么写
print 'a'.encode('hex')
base64编码解码
需要导入base64的库,具体如下
import base64
print base64.b64encode('a')
# 如果要解码改成decode即可
URL编码
导入库实现,如下
from urllib import quote
print quote('select user from users#')
ASCII编码
print map(ord,'<?php phpinfo() php>')
URL格式化输出
有的时候需要提交的包是字典形式,如果自己转换成URL形式很麻烦。使用urllib库解决,方法如下
from urllib.parse import urlencode
data={
user:'admin',
pass:'123456',
age:'50'
}
url = 'http://www.langzi.fun/get?' + urldecode(data)
Python引用(import)文件夹下的py文件的方法
import sys
sys.path.append("..")
import mod1
import mod2.mod2
安装pip
安装python.msi时候没有勾选安装pip的情况下,就不会帮你安装pip的,在cmd下输入命令安装
python -m pip install -U pip setuptools
如果报错的话,到Python pip网站下载get-pip.py 文件,python get-pip.py安装即可。
网络请求
requests
保存cookies,第一步登录你的账户密码获取cookie,然后使用cookie登录
payload = {'username': 'admin', 'password': 'password'}
r = requests.post('http://pythonscraping.com/pages/cookies/welcome.php', data=payload)
print(r.cookies.get_dict())
r = requests.get('http://pythonscraping.com/pages/cookies/profile.php', cookies=r.cookies)
print(r.text)
使用Session自动化管理cookies
同样是执行上面的登录操作, 下面就是使用 session 的版本. 创建完一个 session 过后, 我们直接只用 session 来 post 和 get. 而且这次 get 的时候, 我们并没有传入 cookies. 但是实际上 session 内部就已经有了之前的 cookies 了.
session = requests.Session()
payload = {'username': 'admin', 'password': 'password'}
r = session.post('http://pythonscraping.com/pages/cookies/welcome.php', data=payload)
print(r.cookies.get_dict())
r = session.get("http://pythonscraping.com/pages/cookies/profile.php")
print(r.text)
上传图片
file = {'uploadFile': open('./image.png', 'rb')}
r = requests.post('http://pythonscraping.com/files/processing2.php', files=file)
print(r.text)
自动取消报警
from requests.packages import urllib3
urllib.disable_warning()
爬虫类
- 正则表达式可以一次性获取多个数据,比如标题,连接,评论。分别迭代在一个生成器中。在迭代的时候可以使用item[0],item[1]这样取数据。
- json这个库很常用,不仅是json.loads()与json.dumps(),还有.get(‘data’)这样获取数据。
- 关于AJAX的数据可以抓包在XHR中得到。
- 优先抓包分析网址,分析不同网址之间的关系,没必要每次都获取全部的网页数据。
- 流程设计中,每个模块独立封装在一个函数中,并且使用return返回数值。
- 下载文件的时候,防止重复下载,可以根据md5值来防止重复。下载文件,命名方式为该文件的md5值,然后做个判断,os.path.exists()判断即可。
- 如果必须要得到某个函数的返回结果,可以在该函数中使用递归,在函数的异常处理中return该函数,最后的main()函数中把该函数赋值给一个变量。
- 获取返回的所有数据并且去重复:url_list=set([get_url(x)for x in urls])比如利用bs4库解析url_list=set([job(x[‘href’])for x in urls]),结果result=[get_result(x) for x in ulrs],如果使用多进程的话,muli_res=[pool.apply_async(job,(i,))for i in range(10)]job函数接受一个参数i。如果是在使用一个列表存储网址,在调用网址的时候迭代网址,但是可以使用列表的len()长度判断,每次取出一个网址就删除一个网址,比如unseen=set([base_url,])
编程技巧
原地交换两个数字
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)
:10 20
20 10
链状比较操作符
n = 10
print(1 < n < 20)
print(1 > n <= 9)
//找abc中最小的数
def small(a, b, c):
return a if a<b and a<c else (b if b<a and b<c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))
:0
1
3
3
//列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]
print(x)
:[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
多行字符串
multistr = "select * from multi_row \
where row_id < 5"
print(multistr)
:select * from multi_row where row_id < 5
存储列表元素到新的变量
testList = [1, 2, 3]
x, y, z = testList //变量个数应该和列表长度严格一致
print(x, y, z)
:1 2 3
打印引入模块的绝对路径
import threading
import socket
print(threading)
print(socket)
:<module 'threading' from 'd:\\python351\\lib\\threading.py'>
<module 'socket' from 'd:\\python351\\lib\\socket.py'>
字典/集合推导
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
字典的值为列表
1、值为列表的构造方法
dic = {}
dic.setdefault(key,[]).append(value)
*********示例如下******
>>dic.setdefault('a',[]).append(1)
>>dic.setdefault('a',[]).append(2)
>>dic
>>{'a': [1, 2]}
2、值为字典的构造方法
dic = {}
dic.setdefault(key,{})[value] =1
***********示例如下*********
>>dic.setdefault('b',{})['f']=1
>>dic.setdefault('b',{})['h']=1
>>dic.setdefault('b',{})['g']=1
>>dic
>>{'b': {'h': 1, 'g': 1, 'f': 1}}
字符串转变成字典列表
从网页获取到json后,有些时候类型是字符串,使用eval转成字典即可。如果字典的键值比较多的话,可以另外用一个变量取值。
开启文件分享
python -m http.server
检查python中的对象
test = [1, 3, 5, 7]
print(dir(test))
:['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
简化if语句
# use following way to verify multi values
if m in [1, 2, 3, 4]:
# do not use following way
if m==1 or m==2 or m==3 or m==4:
运行时检测python版本
import sys
if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):
print("sorry, you are not running on python 2.7")
print("current python version:", sys.version)
:sorry, you are not running on python 2.7 current python version: 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
组合多个字符串
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
:['I', 'Like', 'Python']
ILikePython
四种翻转字符串、列表的方式
# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)
# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):
print(element)
# 翻转字符串
print("Test Python"[::-1])
# 用切片翻转列表
print([1, 3, 5][::-1])
用枚举在循环中找到索引
test = [10, 20, 30]
for i, value in enumerate(test):
print(i, ':', value)
:0 : 10
1 : 20
2 : 30
从方法中返回多个值
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
:1 2 3 4
使用*运算符unpack函数参数
def test(x, y, z):
print(x, y, z)
testDic = {'x':1, 'y':2, 'z':3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)
:z x y
1 2 3
10 20 30
计算任何数的阶乘
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
:6
找到列表中出现次数最多的数
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
:4
重置递归限制
python限制递归次数到1000,可以用下面方法重置
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
:1000
1200
检查一个对象的内存使用
import sys
x = 1
print(sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节
:28
搜索字符串的多个前后缀
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
:True
True
不使用循环构造一个列表
import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
:
[-1, -2, 30, 40, 25, 35]
实现switch-case语句
def xswitch(x):
return xswitch._system_dict.get(x, None)
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))
:None
2
欢迎关注公众号:【安全研发】获取更多相关工具,课程,资料分享哦~