3-1 人生苦短,我用Python
3-2 Python 安装与配置
...\LIb\site-packages
PyCharm安装
Pycharm是一种IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、
代码跳转、智能提示、自动完成、单元测试、版本控制。此外,该IDE提供了一些高级功能。以用于支持Django框架下的专业
Web开发。
官网下载地址(选择社区版):
http://www.jetbrains.com/pycharm/download/#section=windows
3-3 第一个Python程序
''' # print语句 # 打印字符串 print ("hello world!") print ("are","you","ok") #打印整数 print(500) print(500+200) #打印变量 name="123" print("hello,%s" %name) width=30 print("width is %d " %width) ''' #input语句 con=input("please input Contten: ") print("the input Content is %r" %con)
3-4 Python常用数据类型
整数
x=5
y=5
z=x+y
print(z)
浮点数
f=5.20
l=5.30
a=f+l
print(a)
字符串
str="hello world"
print(str)
转义字符
print("hello \n world")
print("c:\\python35")
#my name is 'Jack' and "you" print("My name is \'Jack\' and \"your\"")
布尔值
t=True f=False print(t and f)
3-5 数组定义与访问
数组是一种有序的集合,可以随时添加和删除其中的元素。
数组定义
student =['jack','bob','harry','Micle'] print(student) #访问数组元素,用索引来访问数组中的每一位元素值,记得索引是从0开始的 print(student[0]) print(student[1]) #访问数组最后一个元素 #注意,当索引超过范围时,Python会报一个Index Error错误,所以,要确保索引不要越界 print(student[-1])
3-6 数组元素添加修改与删除
添加元素 #末尾追加元素 student.append("john") print(student) #在指定位置添加元素 student.insert(0,'tom') print(student) 修改元素 student[0]='No.1' print(student)
删除元素
#删除末尾元素
student.pop()
print(student)
#删除指定位置元素
student.pop(1)
print(student)
3-7 Python元组数据
course=('Chinese','Math','Englist','compuuter') print(course) print(course[1:3]) print(course[-1]) print(course[1:]) print(course[:2]) #元组的个数 print(len(course)) #定义一个只有1个元素的元组,则需要在元素后面加逗号,用来消除数据歧义 t=(1,) #返回元组最大值 score=(78,90,88,76,78) print(max(score))
3-8 python字典
student = {1:'jack',2:'bob',3:'marry',4:'Micle'} print(student[3]) #添加元素 #增加新的键值对 student[5]='hello' print(student) #修改元素 #修改字典 student[2]='Marry' print(student) #删除字典 del student[1] print(student) #清空字典全部内容 student.clear() print(student) #删除字典 del student
3-9 条件判断
score = 80 if score >=80: print("score is A") else: print("score is not A")
注意:print语句要注意,不要Tab和空格混合使用,否则会编译报错
score = 80
if score >= 80:
print("score is A")
elif score>=60:
print("score is not B")
else:
print("score is C")
Tips:elif是else if的缩写,完全可以有多个elif
3-10 循环语句
student=('Jack','Bob','Marry','Micle')
for stu in student:
print (stu)
案例2:计算1+2+3+...10的值
sum = 0
for i in range(11):
sum += i
print(sum)
n=10
while n>0:
n=n-1
print(n)
print('over')
3-11 Python 猜数字小游戏
import random
#生成随机数
answer = random.randint(1,100)
#家输入数值
n=int(input("Please input num()1-100:"))
#判断输入数字大小
while n!=answer:
if n>answer:
n=int(input("Num is more Please Continue input num:"))
elif n<answer:
n=int(input("Num is less Please Continue input num:"))
#输出答案正确,程序退出
print("You win the game!")
3-12 Python函数定义与调用
def Max_num (a,b):
if a>b:
return a
elif a<b:
return b
else:
return a
result = Max_num(15,100)
print((result))
3-13 Python 面向对象(1)
name='Jack'
city='Beijing'
print("My name is %s and come from %s" %(name,city))
print("hello,python")
name='Harry'
city='Shanghai'
print("My name is %s and come from %s" %(name,city))
print("hello,python")
3-14 Python面向对象(2)
3-15 Python类与对象
class Student():
def __init__(self,name,city):
self.name=name
self.city=city
print("My name is %s and come from %s" %(name,city))
class Student():
def __init__(self,name,city):
self.name=name
self.city=city
print("My name is %s and come from %s" %(name,city))
def talk(self):
print("hello python")
class Student():
def __init__(self,name,city):
self.name=name
self.city=city
print("My name is %s and come from %s" %(name,city))
def talk(self):
print("hello python")
stu1=Student('Jack','Beijing')
stu1.talk()
stu2=Student('Micle','Shanghai')
stu2.talk()
3-16 Python模块引用
#模块 显示当前时间
import time
print(time.ctime()) #调用获取当前时间方法
导入随数模块显示随机整数
from time import sleep
sleep(5)
print("Sleep over!")
3-17 跨目录模块引用
from student import Student
stu1=Student('Jack','Beijing')
stu1.talk()
stu2=Student('Micle','Shanghai')
stu2.talk()
from school.student import Student
stu1=Student('Jack','Beijing')
stu1.talk()
stu2=Student('Micle','Shanghai')
stu2.talk()
3-18 Python异常(1)
try:
print(stu)
except BaseException as msg:
print(msg)
try:
fileName=input("please input fileName:")
open("%s.txt" %fileName)
except FileNotFoundError:
print("%s.txt file not found" %fileName)
try:
print(stu)
except NameError:
print("stu not define")
BaseException
try:
print(stu)
except BaseException:
print("stu not define")
3-19 Python异常(2)
try:
print(stu)
except BaseException as msg:
print(msg)
try:
stu= "jack"
print(stu)
except BaseException as msg:
print(msg)
else:
print("stu is defined")
try...excepy...finally输出
try:
stu= "jack"
print(stu)
except BaseException as msg:
print(msg)
finally:
print("The end !")
raise 抛出异常
前面try语句是执行过程中捕获代码块的异常,而else是通过事先定义一个条件,一旦符合异常条件就抛出异常。
def division(x,y):
if y==0:
raise ZeroDivisionError("Zero is not allow!")
return x/y
try:
division(8,0)
except BaseException as msg:
print(msg)
注意:raise 只能用于Python标准异常类
BaseException 所有异常的基类
SystemExit 解释器请求退出
3-20 文件处理
打开文件
使用Python内置的方法open()可以打开文件
File object = open(file_name [,access_mode][,buffering])
file_name: file_name变量是一个包含了你要访问的文件名称的字符串值。
access_mode:access_mode 决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个
参数是非强制的,默认文件访问模式为只读的(r)。
buffering:如果buffering的值设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
f1=open("aa.txt",'r')
f2=open('D:\\python\\selenium自动化测试\\ch3\\aa.txt','r')
常用文件打开模式
模式 描述
r 以只读方式打开文件
rb 以二进制格式打开一个文件用于只读
w 打开一个文件只用于写入
a 打开一个文件用追加。新的内容会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
文件读取
line=f1.read()
line1=f1.readline()
line2=f1.readlines()
read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。
readline()每次只读取一行
readlines()一次性读取文件所有行 自动将文件内容分析成一个行的列表, 该列表可以由Python 的for...in...结构进行处理
关闭文件
f.close()
3-21 读取txt文件
f=open("stu_Info.txt",'r')
lines=f.readlines()
print(lines)
for line in lines:
print(line.split(',')[0])
['Jack,22,Beijing\n', 'Micle,33,Shanai\n', 'John,23,Shenzhen\n'] Jack Micle John
split()方法语法
str.split(str="",num=string..count(str))
参数
str --分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num --分割次数
3-22 读写csv文件
csv即为逗号分隔值(Comma-Separated Calues, VSV),有时也称为字符分隔值,其文件以纯文本形式存储表格数据(数字和文本)。
csv文件读取
案例:读取stu_info.csv 文件里所有学生信息。.
import csv
csv_file=csv.reader(open('stu_info.csv','r'))
for stu in csv_file:
print(stu)
csv_file=csv.reader(open('stu_info.csv','r'))
for stu in csv_file:
print(stu[0])
csv_file=csv.reader(open('stu_info.csv','r'))
for stu in csv_file:
print(stu[1])
csv_file=csv.reader(open('stu_info.csv','r'))
for stu in csv_file:
print(stu[2])
stu=['Marry',28,'Changsha']
stu1=['Rom',23,'Chendu']
#打开文件
out=open('stu_info.csv','a',newline='')
#设定写入模式
csv_write=csv.writer(out,dialect='excel')
#写入具体内容
csv_write.writerow(stu)
csv_write.writerow(stu1)
print("Write file over")
3-23 xml文件概述
document.title ='hello';
3-24 手工打造一个xml文件
<?xml version="1.0" encoding="utf-8" ?>
<class>
<student>
<name>Jack</name>
<age28></age28>
<city>Beidjing</city>
</student>
<student>
<name>Bob</name>
<age>25</age>
<city>Shanghai</city>
</student>
<student>
<name>Harry</name>
<age>23</age>
<city>Shenzhen</city>
</student>
<teacher>
<name>Marry</name>
<age>23</age>
<city>Changsha</city>
</teacher>
<account>
<login username="teacher" password="12345690"/>
<login username="student" password="888888"/>
</account>
</class>
3-25 读取xml元素节点
- nodeName(节点名称)
- nodeValue(节点值)
- nodeType(节点类型)
from xml.dom import minidom
#打开xml文件
dom=minidom.parse('class.xml')
#加载dom对象元素
root = dom.documentElement
#打印节点信息
print(root.nodeName)
print(root.nodeValue)
print(root.nodeType)
输出结果
C:\python35\python.exe D:/python/selenium自动化测试/ch3/get_node_info.py
class
None
1
- nodeName:节点名称
- nodeValue:返回文本节点的值
- nodeType:属性返回以数字值返回指定节点的节点类型
3-26 读取xml文本节点
from xml.dom import minidom
#打开xml文件
dom=minidom.parse('class.xml')
#加载dom对象元素
root = dom.documentElement
#根据标签名称获取标签对象
names=root.getElementsByTagName('name')
ages=root.getElementsByTagName('age')
cities=root.getElementsByTagName('city')
#分别打印显示xml文档标签对里面的内容
for i in range(4):
print(names[i].firstChild.data)
print(ages[i].firstChild.data)
print(cities[i].firstChild.data)
输出结果
C:\python35\python.exe D:/python/selenium自动化测试/ch3/get_node__value.py
Jack
25
Beidjing
Bob
25
Shanghai
Harry
23
Shenzhen
Marry
23
Changsha
3-27 读取xml属性节点
from xml.dom import minidom
#打开xml文件
dom=minidom.parse('class.xml')
#加载dom对象元素
root = dom.documentElement
logins=root.getElementsByTagName('login')
for i in range(2):
username=logins[i].getAttribute('username')
print(username)
password=logins[i].getAttribute('password')
print(password)
输出结果
C:\python35\python.exe D:/python/selenium自动化测试/ch3/get_node_attriibute.py
teacher
12345690
student
888888
3-28 读取xml子节点
from xml.dom import minidom
#打开xml文件
dom=minidom.parse('class.xml')
#加载dom对象元素
root = dom.documentElement
tags= root.getElementsByTagName('student')
print(tags[0].nodeName)
print(tags[0].tagName)
print(tags[0].nodeType)
print(tags[0].nodeValue)
输出结果
C:\python35\python.exe D:/python/selenium自动化测试/ch3/get_child_node_info.py
student
student
1
None
3-29 线程与进程概述
线程与进程的区别
线程和进程的区别在于,子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程
有自己的执行堆栈和程序计数器为其执行上下文。
Tips:
LoadRunner和Jmeter性能测试工具也利用了多线程和多进程来构造多个并发用户来执行性能测试
线程与进程图文解释
http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html
3-30 单线程实践应用
from time import ctime,sleep
#说
def talk():
print("Start talk: %r" %ctime())
sleep(2)
#写
def write():
print("Start write %r" %ctime())
sleep(3)
if __name__=='__main__':
talk()
write()
print("All end ! %r" %ctime())
3-31 多线程实践应用
from time import ctime,sleep
import threading
#定义和写的方法
def talk(content,loop):
for i in range(loop):
print("Start talk:Hello:%s %s" %(content,ctime()))
sleep(3)
def write(content,loop):
for i in range(loop):
print("Start write:Hello:%s %s" %(content,ctime()))
sleep(5)
#定义和加载说和写的线程
threads=[]
t1=threading.Thread(target=talk,args=('hello world!',2))
threads.append(t1)
t2=threading.Thread(target=write,args=('Life is short,you need Python!!',2))
threads.append(t2)
#执行多线程
if __name__=='__main__':
for t in threads:
t.start()
for t in threads:
t.join()
print("All Thread end! %s" %ctime())
C:\python35\python.exe D:/python/selenium自动化测试/ch3/multi_threading.py
Start talk:Hello:hello world! Thu Dec 14 15:31:23 2017
Start write:Hello:Life is short,you need Python!! Thu Dec 14 15:31:23 2017
Start talk:Hello:hello world! Thu Dec 14 15:31:26 2017
Start write:Hello:Life is short,you need Python!! Thu Dec 14 15:31:28 2017
All Thread end! Thu Dec 14 15:31:33 2017
3-22 多进程实践应用
与多线程相比,多进程就是import multiprocessing 然后替换相应的方法
multiprocessing.Process()
from time import ctime,sleep
import multiprocessing
#定义和写的方法
def talk(content,loop):
for i in range(loop):
print("Start talk:Hello:%s %s" %(content,ctime()))
sleep(3)
def write(content,loop):
for i in range(loop):
print("Start write:Hello:%s %s" %(content,ctime()))
sleep(5)
#定义和加载说和写的进程
process=[]
p1=multiprocessing.Process(target=talk,args=('hello world!',2))
process.append(p1)
p2=multiprocessing.Process(target=write,args=('Life is short,you need Python!',2))
process.append(p2)
#执行多进程
if __name__=='__main__':
for t in process:
t.start()
for t in process:
t.join()
print("All process is run OK! %s" %ctime())
import urllib
import urllib.request
import urllib.response
import re
def load_page(url):
request=urllib.request.Request(url)
response=urllib.request.urlopen(request)
data=response.read()
return data
def get_image(html):
regs=r'http://[\S]*jpg'
patter=re.compile(regs)
get_image=re.findall(patter,repr(html))
num=1
for img in get_image:
image=load_page(img)
with open('D:\\Photo\\%s.jpg' %num,'wb') as fb:
fb.write(image)
print("正在下载第%s张图片" %num)
num=num+1
print("下载完成")
url='http://p.weather.com.cn/2017/06/2720826.shtml#p=1'
html=load_page(url)
get_image(html)