使用hex(‘a’)是不行的,如果想要对字符串hex编码可以这么写
print 'a'.encode('hex')
需要导入base64的库,具体如下
import base64
print base64.b64encode('a')
# 如果要解码改成decode即可
导入库实现,如下
from urllib import quote
print quote('select user from users#')
print map(ord,'')
有的时候需要提交的包是字典形式,如果自己转换成URL形式很麻烦。使用urllib库解决,方法如下
from urllib.parse import urlencode
data={
user:'admin',
pass:'123456',
age:'50'
}
url = 'http://www.langzi.fun/get?' + urldecode(data)
import sys
sys.path.append("..")
import mod1
import mod2.mod2
安装python.msi时候没有勾选安装pip的情况下,就不会帮你安装pip的,在cmd下输入命令安装
python -m pip install -U pip setuptools
如果报错的话,到Python pip网站下载get-pip.py 文件,python get-pip.py安装即可。
保存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()
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 a10 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)
:
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
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']
# 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:
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
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]
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