Python爬虫编程基础5天速成(2022更新)Python入门+数据分析

python 学习(10天)
1.python基础
(1)python:蟒蛇的意思;解释型语言;面向对象;py3.0是主流;
TIOBE:编程语言流行程度排名统计。
(2)缺点:运行速度慢;代码不能加密。
(3)典型应用
脚本、爬虫、AI、WEB、数据分析、数据可视化
2.python环境
略
3.python
print("this is %d"%d)
\t space \n 换行
input()默认输入为str类型。
强制类型转换。
4.运算
in
not in
is
is not
5.条件
if :
elif :
else :
缩进很重要!每次都用TAB。
import random 引入随机库
random.randint(x,y)x和y之间(包括xy)的随机整数。
6.import vs from import
practice:

运行结果:





代码:import random Rand_number= random.randint(0,2) Usrinput=input("请输入:剪刀(0)、石头(1)、布(2):") if Usrinput.isdecimal(): #是否十进制数 Usrinput=int(Usrinput); else:#不是则提示后退出 print("输入错误!") exit() if Usrinput<0 or Usrinput >2: #是否在012的范围内,不是则提示退出 print("输入错误!") exit() if Usrinput == 0: #根据数字判断出的是什么 print("你的输入为:剪刀(0)") elif Usrinput == 1: print("你的输入为石头(1)") else: print("你的输入为:布(2)") print("随机生成数字:%d"%Rand_number) if Usrinput > Rand_number: print("恭喜你赢了") elif Usrinput < Rand_number: print("哈哈你输了") else: print("平手")
7.for循环
(1)for i in range(5)
print(i)
output: 1 2 3 4 5
(2)for i in range(0,10,3)# for(i=0;i<10;i=i+3)
print(i)
output:0 3 6 9
(3)name ="chengdu"
for x in name:
print(x)
output:c h e n g d u
(4)a=["aa","bb","cc","dd"] 列表
for i in range(len(a))
print(i,a[i])
output:0 aa
1 bb
2 cc
3 dd
8.while
i=0
while i<5:
print("当前是第%d次循环"%(i+1))
print("i=%d"%i)
i+=1
【1-100求和】

while count <5:
print(count ,"<")
else:
print(count,">=")
8.break、continue、pass
break:出循环体
continue:跳过当前这一循环
pass:占位语句,没用。
PRACTICE:

运行结果:

代码:for i in range(1,10,1): for j in range(1,i+1,1): print("%d*%d=%d"%(i,j,i*j),end=" ") print()
字符串
string:单引号、双引号、三引号。UTF-8编码。支持拼接、截取。
word=‘字符串’
sentence="this is a sentence"
paragraph="""
this is a paragraph
"""
mystr='I\'m a student'
\+" 或者\+'

str=”chengdu“
print(str) chengdu
print(str[0:6]) # [起始位置(默认为0):结束位置(默认为字符长度):步进值]
chengd
print(str[1:7:2]) hnd
print(str[6:])
连接:
print(str + "你好")
print(str * 3)
output: chengduchengduchengdu
print(r"hello\nchengdu") #r消解转义字符的功能
output:hello\nchengdu
常见操作(注意图中加黑的):


判断输入是否非法:


List(列表)
1.类似数组但不是数组,可以把不同类型的混成一个数组。
2.0是开始值,-1是末尾值。
3.+连接,*表示重复。
4,逗号分隔开。
demo:
namelist=[] #定义一个空列表
namelist=["a","b","1"] #列表可以存储混合的类型
print(namelist[0])
output:a
for i in namelist: #遍历
print(name)
while i<length:
print(namelist[i])
i+=1
常用操作(增删改查)


+:namelist.append(x) #末尾追加一个元素
如果x是一个列表,会被作为一个元素追加进去。
nameilist.extend(列表)#将列表中每个元素加进去。
insert:
namelist.insert(x,y) #把y插入到下标x的位置
delete:
del namelist[i] #删除下标为i的元素
namelist.pop() #弹出末尾最后一个元素
namelist.remove("内容")#根据内容删除!但是只能删除第一个内容(如果有2个重复内容的话)
查找:
1.if...in...

2.index
namelist.index("object",start,end)#寻找object在下标start-end的范围内,并返回一个下标。
范围区间不包含end。(经常左闭右开)
找不到会报错。
3.namelist.count("c") #统计c出现了几次
改变顺序:
1.namelist,.reverse() #直接把原数组顺序颠倒了
2.namelist.sort() #排序 升序
namelist.sort(reverse=true) #降序
嵌套:
namelist=[[],[],[]]#3个列表的空列表
namelist[0][0]

Practice:

运行结果:

代码:
products = [["iphone",6888],["MacPro",14800],["小米6",2499],["Coffee",31],["Book",60],["Nike",699]] print("-------商品列表---------") i=0 for product in products: print("%d %s %d"%(i,product[0],product[1])) i=i+1 shopBasket =[] #购物篮 selectGoods=input("请输入您想购入的商品编号,若无,按q可结算:") while(selectGoods!="q"): #是否为q if selectGoods.isdecimal(): #是否十进制数 selectGoods=int(selectGoods) if selectGoods> len(products)-1:#超出范围的序号 print("该商品不存在!") else: shopBasket.append(products[selectGoods]) else: print("非法输入!") selectGoods=input("请输入您想购入的商品编号,若无,按q可结算:") print("----------购物车----------") sum=0 for goods in shopBasket: print(goods)#结算 sum=goods[1]+sum print("总价",sum)
元组Tuple
不可以修改

tup1=() #create a null tuple
tup2 =(50,)#创建一个50开头的元组,不然会以为tup2是一个整型变量(50)=50
example:
tup1=("abc","def",2000,2020)
print(tup1[0])
print(tup1[-1]) 访问最后一个元素
print(tup1[1:5])(下标1-4)
output:
abd
2020
('def',2000,2020)(左闭右开)
增:
tup1=(12,34,56)
tup2=("ab","cd")
tup=tup1+tup2 #新开辟了一个空间
print(tup)
删:
del tup1#删除整个元组变量,无定义了,不能删某一个值
修改:是不可能的
查:


字典(dict)键-值对

info = {"name":"a","age":"18"}
print(info["name"])
print(info["age"])
output:
a
18
访问了不存在的键会报错,可以采用不直接访问的方式。
print(info.get("gender"))#get方法没找到对应的键默认返回none
Info.get("gender","m")#没找到时的默认值是m
output:
m
新增:
name["id"]=newID

删除:
del info["name"]#删除键值为name的整个键值对
del info #删除了所有键值对
info.clear() #清空了键值对,但还能访问Info
修改:
info["age"]=20
查:
1.查键
info.keys()

2.查值
info.values()
3.查项
info.items()
for key,value in info.items()
print("key=%s,value=%s"%(key,value))
enumerate(X,[start=0])
函数中的参数X可以是一个迭代器(iterator)或者是一个序列,start是起始计数值,默认从0开始。X可以是一个字典。


>>>dict() # 创建空字典
{}
>>> dict(a='a', b='b', t='t') # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}

集合set(去重)


函数
def name(): #定义函数
print(".........")
1.有参数

2.有返回值

3.返回多个值

课堂练习:

全局变量和局部变量:

局部变量优先使用,没有局部变量使用全局。
如果非要使用全局的变量:global x

文件操作
f=open("test.txt","w") #写,没有则新建一个
f=open("test.txt","r")=f=open("test.txt")
rb:二进制读
wb:二进制写
content=f.read(5)#从第一个指针开始读5个字符
content=f.readlines()#一次性读取全部文件为列表,每行一个字符串元素


content=f.readline()#只能读一行

f.close()
import os
os.rename("name","newname")
异常处理
try:
f=open("name.txt","r")
except IOError/NameError: #文件没找到,属于发生IO异常
pass #捕捉异常后应该执行的代码
异常类型想要被捕获,需要一致
except (IOError,NameError)as result#将可能产生的所有异常都放到下面的小括号中
print("wrong")
print(result)

Exception可以承接任何异常

(1)try:
f=open("123.txt","r")
except Exception as result:
print("发生异常")
finally: #一定会被执行
f.close()
print("文件关闭")
(2)

作业:
def FileWrite(gushi,name): f=open(name,"w") f.write(gushi) f.close() def FileRead(name): try: f=open(name,"r") try: content=f.readlines() return content finally: f.close() except Exception as result: print(result) name="gushi.txt" gushi="春种一粒粟,秋收万颗子。\n四海无闲田,农夫犹饿死。\n锄禾日当午,汗滴禾下土。\n谁知盘中餐,粒粒皆辛苦。" FileWrite(gushi,name) content=FileRead(name) name1="copy.txt" contenStr="".join(content) #用join()函数将list转化为字符串 FileWrite(contenStr,name1) FileRead(name1)
爬虫
前置知识:html+css+jsp
1.执行入口:

2.引入模块




urllib:
1.request(GET方法)
response=urllib.request.urlopen("http://www.baidu.com")
return response(网页源代码)
print(response.read().decode('utf-8'))//对获取到的网页源码进行UTF-8解码
2.(POST方法)模拟用户真实登录时使用
一个测试网站:httpbin.org
import urllib.parse
data= bytes(urllib.parse.urlencode{"hello":"world"}),encoding="utf-8")
response=urllib.request.urlopen("http://httpbin.org/post")
print(response.read().decode('utf-8'))//对获取到的网页源码进行UTF-8解码

3.
try: #超时处理
response= urllib.request.urlopen("url",timeout=0.01)
except urllib.error.URLError as e:
print("time out")
4.简单的解析:
print(response.status)
print(response.getheaders())
print(response.getheader("Server"))
5.伪装浏览器
url="..."
headers="User-Agent:......."#把正常浏览器访问的header复制过来
data=bytes(urllib.parse.urlencode({"name":"eric"}),encoding="utf-8")
req = urllib.Request(url=url,data=data,headers=headers,method="POST")
response = urllib.request.urlopen(req)
print(response.read().decode("UTF-8"))
