飞鸟博客

导航

python 学习程序代码:

一. Python 字符串

复习循环:

for letter in 'Runoob':

   if letter == 'o':

      pass

      print ('执行 pass 块')

   print ('当前字母 :', letter)

print ("Good bye!")

# 1.字符串的输入

userName = input('请输入用户名:')

print("用户名为:%s" % userName)

password = input('请输入密码:')

print("密码为:%s" % password)

#2 字符串的输出

name = 'xiaoming'

position = '讲师'

address = '北京市昌平区建材城西路金燕龙办公楼1层'

print('--------------------------------------------------')

print("姓名:%s" % name)

print("职位:%s" % position)

print("公司地址:%s" % address)

print('--------------------------------------------------')

#3 使用切片截取字符串

name="abcdef"

print(name[0:3])  # 取下标0~2 的字符

print(name[3:5])  # 取下标为3、4 的字符

print(name[1:-1]) # 取下标为1开始 到 最后第2个之间的字符

print(name[2:])    # 取下标为2开始到最后的字符

print(name[::-2]) # 倒序从后往前,取步长为2的字符

#4 find函数的使用

mystr ='hello world itheima and itheimaApp'

index=mystr.find("itheima")

print(index)

#5 index函数的使用

mystr ='hello world itheima and itheimaApp'

index=mystr.index("itheima",0,10)

print(index)

#6 count函数

mystr ='hello world itheima and itheimaApp'

result=mystr.count("itheima")

print(result)

#7 replace函数:

mystr ='hello world itheima and itheimaApp'

newStr=mystr.replace("itheima","ITHEIMA",1)

print(newStr)

#8 splite函数

str = "this is string example....wow!!!"

print (str.split( ))

print (str.split('i',1))

print (str.split('w'))

#9 capitalize:第一个字符大写,其他字符小写

mystr ='hello world itheima and itheimaApp'

newStr=mystr.capitalize()

#10 startswith:检查字符串是否以制定子串开头

mystr ='hello world itheima and itheimaApp'

newStr=mystr.startswith("hello")

print(newStr)

#11 endswith:检查字符串是否以制定子串结尾

mystr ='hello world itheima and itheimaApp'

newStr1=mystr.endswith("app")

newStr2=mystr.endswith("App")

print(newStr1)

print(newStr2)

#12 upper函数的使用

mystr ='hello world itheima and itheimaApp'

newStr= mystr.upper()

print(newStr)

#13 ljust:左对齐,使用空格填充至指定长度的新字符串

str = "Runoob example....wow!!!"

print (str.ljust(50, '*'))

#14 rjust:右对齐,使用空格填充至指定长度的新字符串

mystr ='hello world itheima and itheimaApp'

newStr= mystr.rjust(50)

print(newStr)

#15 center:返回一个指定的宽度 width 居中的字符串

mystr ='hello world itheima and itheimaApp'

newStr= mystr.center(50)

print(newStr)

#16 strip函数的使用

mystr='   hello world itheima and itheimaApp   '

newStr= mystr.strip()

print(newStr)

#17 capitalize函数的使用

mystr ='hello world itheima and itheimaApp'

newStr=mystr.capitalize()

print(newStr)

#18 title函数的使用

mystr ='hello world itheima and itheimaApp'

newStr=mystr.title()

print(newStr)

#19 字符串运算符

# 定义两个字符串

str1 = 'bread and '

str2 = 'milk'

print(str1 + str2) # 使用+运算符连接两个字符串

print('-'*15)       # 使用*运算符输出一条横线

print(str1[0])      # 获取索引位置为0的字符

print(str2[0:2])    # 截取索引0~1的字符

i="end"

while True:

  a= input("请输入您要输入的内容但当输入end时结束输入")

  if a.endswith(i):

      print("结束")

      break

print(newStr)

 

二、Python 列表

1.使用索引访问列表元素

A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']

print(A[0])

print(A[1])

print(A[2])

2.使用for循环遍历列表

namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']

for name in namesList:

print(name)

3.使用while循环遍历列表

namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']

length = len(namesList)

i = 0

while i < length:

    print(namesList[i])

    i += 1

4.使用append向列表添加元素

# 定义变量A,默认有3个元素

A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']

print("-----添加之前,列表A的数据-----")

for tempName in A:

    print(tempName)

# 提示并添加元素

temp = input('请输入要添加的学生姓名:')

A.append(temp)

print("-----添加之后,列表A的数据-----")

for tempName in A:

print(tempName)

5.使用extend添加列表元素

a = [1, 2]

b = [3, 4]

a.append(b)

print(a)

a.extend(b)

print(a)

6. 使用insert在列表中插入元素

a = [0, 1, 2]

a.insert(1, 3)

print(a)

7.在列表中查找元素

#待查找的列表

nameList = ['xiaoWang','xiaoZhang','xiaoHua']

#获取用户要查找的名字

findName = input('请输入要查找的姓名:')

#查找是否存在

if findName in nameList:

    print('在列表中找到了相同的名字')

else:

print('没有找到')

8.在列表中修改元素

#定义变量A,默认有3个元素

A = ['xiaoWang','xiaoZhang','xiaoHua']

print("-----修改之前,列表A的数据-----")

for tempName in A:

    print(tempName)

#修改元素

A[1] = 'xiaoLu'

print("-----修改之后,列表A的数据-----")

for tempName in A:

print(tempName)

9.使用del方法删除列表中的元素

movieName = ['加勒比海盗', '骇客帝国', '第一滴血', '指环王', '霍比特人', '速度与激情']

print('------删除之前------')

for tempName in movieName:

    print(tempName)

del movieName[2]

print('------删除之后------')

for tempName in movieName:

    print(tempName)

10. 在列表中删除元素

movieName = ['加勒比海盗', '骇客帝国', '第一滴血', '指环王', '霍比特人', '速度与激情']

print('------删除之前------')

for tempName in movieName:

    print(tempName)

movieName.remove('指环王')

print('------删除之后------')

for tempName in movieName:

    print(tempName)

11. 使用pop删除列表中的最后一个元素

movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']

print('------删除之前------')

for tempName in movieName:

     print(tempName)

movieName.pop()

print('------删除之后------')

for tempName in movieName:

    print(tempName)

12.列表的排序操作

a = [1, 4, 2, 3]

a.reverse()

print(a)

a.sort()

print(a)

a.sort(reverse=True)

print(a)

13.列表的排序

a = [1, 4, 2, 3]

a.reverse()

print(a)

a.sort()

print(a)

a.sort(reverse=True)

print(a)

 

三、Python 元组\字典

修改元祖

tup1 = (12, 34.56);

tup2 = ('abc', 'xyz')

# 以下修改元组元素操作是非法的。

# tup1[0] = 100

# 创建一个新的元组

tup3 = tup1 + tup2;

print (tup3)

 

# tuple=('hello',100,4.5)

# tuple[1]=200

 

2. 元组的遍历

a_turple = (1, 2, 3, 4, 5)

for num in a_turple:

     print(num,end=" ")

 

3.元祖内置函数的使用

tuple1 = ('Google', 'Runoob', 'Taobao')

# 计算元组元素个数

lensize=len(tuple1)

print(lensize)

# 返回元组元素最大值和最小值

tuple2 = ('5', '4', '8')

maxsize=max(tuple2)

minsize=min(tuple2)

print(maxsize)

print(minsize)

# 将列表转为元组

list= ['Google', 'Taobao', 'Runoob', 'Baidu']

tuple3=tuple(list)

print(tuple3)

 

4. 根据键访问字典的值

info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}

# print(info['name'])

# print(info['address'])

age = info.get('age')

print(age)

print(type(age))

age = info.get('age', 18)

print(age)

 

5.修改字典的元素

info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}

newId = input('请输入新的学号')

info['id'] = int(newId)

print('修改之后的id为:%d'%info['id'])

 

6. 添加字典元素

info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}

newId = input('请输入新的学号')

info['id'] = newId

print(info)

7. 使用del删除字典元素

info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}

print('删除前,%s'%info['name'])

del info['name']

print('删除后,%s'%info['name'])

 

8. 使用clear清空字典元素

info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}

print('清空前,%s' % info)

info.clear()

print('清空后,%s' % info)

 

9.计算字典中键值对的个数

dict = {'Name': 'Zara', 'Age': 7};

print("Length : %d" % len (dict))

 

10.获取字典中键的列表

dict = {'Name': 'Zara', 'Age': 7};

print(dict.keys())

 

11.获取字典中值的列表

dict = {'Name': 'Zara', 'Age': 7};

print(dict.values())

 

12.计算字典中键值对的个数

dict = {'Name': 'Zara', 'Age': 7};

print("Length : %d" % len (dict))

 

13.遍历字典的键key

dict = {'Name': 'Zara', 'Age': 7}

for key in dict.keys():

          print(key)

 

14.遍历字典的值value

dict = {'Name': 'Zara', 'Age': 7}

for value in dict.values():

     print(value)

 

15. 遍历字典的元素

dict = {'Name': 'Zara', 'Age': 7}

for item in dict.items():

     print(item)

 

16.遍历字典的键值对

dict = {'Name': 'Zara', 'Age': 7}

for key,value in dict.items():

print("key=%s,value=%s"%(key,value))

 

四、函数应用

局部变量.: 

def test1():

   a=40

   print("test1修改前:a=%d"%a)

   a=100

   print("test1修改后:a=%d"%a)

def test2():

   a=200

   print("test2函数:a=%d"%a)

#调用函数

test1()

test2()

  

递归函数

def fn(num):

    if num==1:

        result=1

    else:

        result= fn(num-1)*num

    return  result

n=int(input("请输入一个正整数:"))

print("%d!="%n, fn(n))

 

日期时间日历函数:

import time;  # 引入time模块

print("1.输出时间戳")

ticks = time.time()

print("当前时间戳为:", ticks)

 

print("2.接收时间戳输出元组")

print(time.gmtime(time.time()))

print(time.localtime(time.time()))

 

print("3.接收元组戳输出格式化日期")

print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) #接收元组

print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime(time.time())))

 

print("-------日历---------")

import  calendar

print(calendar.calendar(2019))

 

 

随机函数:

 

import random

# 生成第一个随机数

print("random():", random.random())

# 生成第二个随机数

print("random():", random.random())

 

-------------------

print("random:",random.uniform(50,100))

 

print("random:",random.uniform(100,50))

 

#生成的随机数n: 12 <= n <= 20

print(random.randint(12,20))

#结果永远是20

print(random.randint(20,20))

#print random.randint(20, 10)   #该语句是错误的。下限必须小于上限。

 

 import random

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

slice = random.sample(list, 5)

print(slice)

print(list)

五、爬虫应用

典型应用一:

# 1.通过requests向百度首页发送请求,获取百度首页的数据。

# 导入requests库

import requests

# 请求的URL路径和查询参数

url = "http://www.baidu.com"

# 请求报头

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"

}

# 发送GET请求,返回一个响应对象

response = requests.get(url)

# 查看响应的内容

print(response.text)

 

 

# 2.通过requests向百度首页发送请求查询”测试数据",获取百度查询页的数据。

# # 导入requests库

# import requests

# # 请求的URL路径和查询参数

# url = "http://www.baidu.com/s"

# param = { "wd":"测试数据"}

# # 请求报头

# headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"

# }

# # 发送GET请求,返回一个响应对象

# response = requests.get(url, params=param, headers=headers)

# # 查看响应的内容

# print(response.text)

 

# 3.把www.baidu.com的图片保存到本地。

# import requests

# # 图片的Url

# url="https://www.baidu.com/img/bd_logo1.png"

# # 响应本身是一个图片,并且是二进制类理

# response=requests.get(url)

# # print(response.content)

# # 以二进制+写入方式打开文件

# with open('baidu.png','wb') as f:

#     # 写入respone.content bytes二进制类型

#     f.write(response.content)

 

# 4.requests发送带header的请求

 

典型应用二:

from lxml import etree

# 1.xml库使用

print("1.xml库使用")

text= '''<div>

    <ul>

         <li class="item-0"><a href="link1.html">第一个</a></li>

         <li class="item-1"><a href="link2.html">second item</a></li>

         <li class="item-0"><a href="link5.html">a属性</a></li>

     </ul>

 </div>'''

# (1)etree.formstring()函数读取文本解析节点

print("(1)formstring()函数读取文本解析节点")

print("formstring()函数将文本解析成为Element对象:")

fromstr=etree.fromstring(text)

print("formstring()函数将文本解析成为Element对象后:",fromstr)

print("将Element对象解析成为文本:")

resultfromstr=etree.tostring(fromstr,encoding='utf-8')

print("将Element对象解析成为文本后:",resultfromstr)

# (2)etree.HTML()函数读取文本解析节点

print("(2)etree.HTML()函数读取文本解析节点")

print("etree.HTML()函数将文本解析成为Element对象:")

html=etree.HTML(text)

print("etree.HTML()函数将文本解析成为Element对象后:",html)

resulthtml=etree.tostring(html,encoding='utf-8')

print("将Element对象解析成为文本后:",resulthtml)

 

# 2.lxml库find()方法,findall()方法,interfind()方法

print(" 2.lxml库find()方法,findall()方法,interfind()方法使用")

print("find查找html节点:",html.find("."))

print("find查找body节点:",html.find("./body"))

print("find查找body/div节点:",html.find("./body/div"))

print("find查找body/div/ul节点:",html.find("./body/div/ul"))

print("find查找body/div/ul/li节点:",html.find("./body/div/ul/li"))

print("find查找body/div/ul/li/a节点:",html.find("./body/div/ul/li/a"))

print("findall查找body/div/ul节点结果是一个列表:",html.findall("./body/div/ul"))

print("迭代器查询的使用:")

liList=html.iterfind("./body/div/ul/li")

print("迭代器查询后输出:",end=" ")

for li in liList:

    print(li.xpath("./a/text()")[0],end="  ")

print("\n")

 

# 3.xpath用法

print("3.xpath用法")

print("(1).xpath用法选取节点")

print("xpath用法选取html节点:",html.xpath("."))

print("xpath用法选取body节点:",html.xpath("./body"))

print("xpath用法选取body/div节点:",html.xpath("./body/div"))

print("xpath用法选取body/div/ul/li节点:",html.xpath("./body/div/ul/li"))

print("xpath用法'//'不考虑位置选取/div节点:",html.xpath("//div"))

print("xpath用法'..'选取li 父节点:",html.xpath("//li/.."))

 

print("(2).xpath用法选取@属性")

print("xpath用法'@属性'选取//a/@href 属性:",html.xpath("//a/@href"))

 

print("(3).xpath用法选取谓语")

print("xpath用法'@属性=值'选取//li[@class='item-0']选谓语 :",html.xpath("//li[@class='item-0']"))

print("(4).xpath用法选取未知节点")

print("xpath用法'ul/*'选取ul元素下所有元素 :",html.xpath("//ul/*"))

print("xpath用法所有li带属性的元素 :",html.xpath("//li[@*]"))

print("xpath用法根元素下所有节点 :",html.xpath("//node()"))

print("(5).xpath用法选取若干路径")

print("xpath用法'|'选取若干路径 :",html.xpath("//li[@class='item-0']|//li[@class='item-1']"))

 

------------抓取163即时新闻-------------

import requests

from lxml import etree

url="https://news.163.com/domestic/"

response=requests.get(url)

response.encoding="gb2312"

# txt=response.text

html=etree.HTML(response.text)

liList=html.xpath("//div[@class='today_news']/ul/li")

print("163今日推荐------------")

for li in liList:

     print( li.xpath("./a/text()")[0],"\n")

     print( li.xpath("./a/@href")[0],"\n")

print("163即时新闻------------")

liList2=html.xpath("//div[@class='mt23 mod_jsxw']/ul/li")

for li in liList:

     print( li.xpath("./a/text()")[0],"\n")

     print( li.xpath("./a/@href")[0],"\n")

 

# 4.抓取广州城建职业学院网站上学院新闻栏目下的新闻列表

print("4.抓取广州城建职业学院网站上学院新闻栏目下的新闻列表")

import requests

from lxml import etree

response =requests.get("http://www.gzccc.edu.cn/xwzx/cjyw.htm")

response.encoding="utf-8"

html=etree.HTML(response.text)

newList=html.xpath("//a[@class='c18915']")

# print(newList)

for li in newList:

    title=li.xpath("./text()")[0] #xpath抓取得到的是一个列表,加[0]读取的是第0个元素

    href=li.xpath("./@href")[0]

    time=li.xpath("../../td[3]/span/text()")[0]

    # f=open("gzccc.txt",'a',encoding="utf-8")

    # f.write(title+href+time+"\n")

    # f.close()

    with open("gzccc.txt",'a',encoding="utf-8") as f:

        # 写入respone.content bytes二进制类型

        f.write(title+href+time+"\n")

    print(title,href,time)

 

爬虫代码:

典型应用三:

#1.抓取河南商贸职业学院的新闻

import requests

from lxml import etree

def get_data(url):

      resp=requests.get(url)

      resp.encoding="utf-8"

      return etree.HTML(resp.text)

 

def printContent(pagCnt,content):

    num=1

    li_list=content.xpath("//div[@class='artic_t_1 ny_news_lb']/ul/li")

    for li in li_list:

        title=li.xpath("./a/text()")

        href=li.xpath("./a/@href")

        time=li.xpath("./span/text()")

        print( pagCnt*20 + num,title,time,href)

        num=num+1

        f=open("1.txt","a",encoding="utf-8")

        f.write(str(pagCnt*20 + num)+ str(title)+ str(time)+ str(href)+"\n")

 

pagCnt = 0

str_url= "http://www.hnjmxy.cn/xwdt/xyxw.htm"

content= get_data(str_url)

while True:

    nextpage=content.xpath("//a[@class='Next']")

    pagCnt=pagCnt+1

    print("--------这是nextpage--",nextpage)

    if len(nextpage) != 0:

        href=nextpage[0].xpath("./@href")[0]

        text=nextpage[0].xpath("./text()")[0]

        # print (href)

        # print (text)  #显示下页文字

        if str(href).find("/") > 0:

            str_url="http://www.hnjmxy.cn/xwdt/"+href    #如果href是xyxw/2.htm这种形式

        else:

            str_url="http://www.hnjmxy.cn/xwdt/xyxw/"+href   #如果href是2.htm这种形式

        print(str_url)

        content= get_data(str_url)

        printContent(pagCnt,content)

    else:

        break

#2. 抓取广州城建职业学院学校新闻的代码

import requests

from lxml import etree

def get_data(url):

    resp=requests.get(url)

    resp.encoding="utf-8"

    return etree.HTML(resp.text)

url="http://www.gzccc.edu.cn/xwzx.htm"

def printContent(pagCnt,content):

    num=1

    li_list=content.xpath("//table[@class='winstyle18915']/tr")

    for li in li_list:

        title=li.xpath("./td[2]/a/text()")

        href=li.xpath("./td[2]/a/@href")

        time=li.xpath("./td[3]/span/text()")

        print(pagCnt * 12 + num, title, time, href)

        num=num+1

        # f=open("e:\\shiye\\gzccc.txt","a",encoding="utf-8")

        # f.write(str(pagCnt*12+num)+str(title[0])+str(time[0])+str(href[0])+"\n")

pagCnt=0

str_url="http://www.gzccc.edu.cn/xwzx.htm"

content=get_data(str_url)

 

while True:

    nextpage=content.xpath("//a[@class='Next']")

    pagCnt=pagCnt+1

    print("--------这是nextpage--", nextpage)

    if len(nextpage)!=0:

        href=nextpage[0].xpath("./@href")[0]

        text=nextpage[0].xpath("./text()")[0]

        if str(href).find("/") > 0:

            str_url = "http://www.gzccc.edu.cn/" + href  # 如果href是xyxw/2.htm这种形式

        else:

            str_url = "http://www.gzccc.edu.cn/xwzx/" + href  # 如果href是2.htm这种形式

        print(str_url)

        content = get_data(str_url)

        printContent(pagCnt, content)

    else:

        break

 

六、selenium 自动化测试

# 1.selenium的基本使用(需要安装chromedriver

print("1.selenium的基本使用")

# selenium使用

# from selenium import  webdriver

# driver=webdriver.Chrome()

# driver.get("http://www.baidu.com")

# data=driver.find_element_by_id("wrapper").text

# print(data)

# print(driver.title)

# driver.save_screenshot("baidu.png")#截屏保存

# print(driver.page_source)#页面源代码

# driver.find_element_by_id("kw").send_keys(u"长城")

# driver.save_screenshot("baidu.png")

# driver.find_element_by_id("su").click()

# driver.save_screenshot("changcheng.png")

 

# 2.使用selenum模拟登录广州城建学院网站,并打印源代码"

print("2.使用selenum模拟登录gzccc")

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

import time

driver=webdriver.Chrome()

driver.get("https://cas.gzccc.edu.cn/lyuapServer/login")

elem=driver.find_element_by_name("username")

elem.clear()

elem.send_keys("8888")

password=driver.find_element_by_name("password")

password.clear()

password.send_keys("88888")

input('请在网页上输入验证码,完成以后回到这里继续。')

elem.send_keys(Keys.RETURN)

time.sleep(1)

print(driver.page_source)

driver.quit()

posted on 2019-06-02 21:04  飞鸟博客  阅读(458)  评论(0编辑  收藏  举报