1.字符串基礎(chǔ)
①字符串的加法和乘法
a = 'I'
b = ' love'
c = ' Scrapy'
d = '!'
print(a + b + c + d*3)
結(jié)果: I love Scrapy!!!
②字符串的切片和索引
a = 'I love Scrapy!!!'
print(a[0],a[0:6],a[-1])
結(jié)果: I I love !
③字符串方法
split()方法:分割空字符或指定的字符,返回列表形式
strip()方法:去除首尾空字符或指定的字符
replace()方法:替換指定字符串
format()方法:字符串格式化符
a = " www..baidu..com "
link = a.strip().replace("..",".").split(".")
print(link)
分析: www..baidu..com→www.baidu.com→['www', 'baidu', 'com']
結(jié)果: ['www', 'baidu', 'com']
2.函數(shù)與控制語(yǔ)句
①函數(shù)
def func(參數(shù)1,參數(shù)2...):
return 結(jié)果
②判斷語(yǔ)句
if...else...
if...elif...else... #多重條件
③循環(huán)語(yǔ)句
for item in iterable: #方式一
pass
for i in range(1:10): #方式二
print(i)
while 條件: #方式三
執(zhí)行語(yǔ)句
3.Python數(shù)據(jù)結(jié)構(gòu)
①列表:爬蟲實(shí)戰(zhàn)中使用最多的數(shù)據(jù)結(jié)構(gòu)。例如構(gòu)造多個(gè)URL,保存爬取到的數(shù)據(jù)等。
- 常用方式一:列表+多重循環(huán)
names = ["張三","李四","王五"]
ages = [6,7,8]
for name,age in zip(names,ages):
print(name,age,end='| ')
結(jié)果: 張三 6|李四 7|王五 8|
- 常用方式二:構(gòu)造URL
urls = ['http://www.top123.com/{}-8'.format(i) for i in range(1,5)]
for url in urls:
print(url)
結(jié)果:
http://www.top123.com/1-8
http://www.top123.com/2-8
http://www.top123.com/3-8
http://www.top123.com/4-8
②字典:搭配數(shù)據(jù)庫(kù)使用,此處僅列出字典的創(chuàng)建。
users_info = {'張三': 6, '李四': 7, '王五': 8}
③元組和集合:元組和集合較少使用。
其中,集合的元素?zé)o序,且無(wú)重復(fù)對(duì)象,可用于去除重復(fù)對(duì)象。
list1 = ['I','You','I']
set1 = set(list1)
print(set1)
結(jié)果: {'I', 'You'}
4.Python文件操作
f = open("F:/d.txt",'w+')
f.write("Hello!")
content = f.read()
print(content)
f.close()
此時(shí)打印無(wú)結(jié)果,因?yàn)閷懭氲臄?shù)據(jù)還保存在緩存中,直至執(zhí)行完f.close()。
更推薦下面的寫法:
with open("F:/d.txt",'r+') as f:
content = f.read()
print(content)
f.close()
- open()函數(shù)中模式參數(shù)的常用值
| 值 | 描述 |
|---|---|
| 'r' | 讀模式 |
| 'w' | 寫模式 |
| 'a' | 追加模式 |
| 'b' | 二進(jìn)制模式,用于圖片、視頻等,例如'wb'可用于下載視頻。 |
| '+' | 讀/寫模式,可與其他模式疊加,例如'a+','wb+'等。 |
5.Python面向?qū)ο?/h2>
①定義類:類名首字母一般大寫。 class Bike:
②實(shí)例屬性 Bike.other
③實(shí)例方法 Bike.use()
④類的繼承 class Share_bike(Bike):
⑤類的魔術(shù)方法,例如: def __init__(self):
class Bike:
Bike.other
Bike.use()
class Share_bike(Bike):
def __init__(self):
完整例子:
class Bike:
compose = ['frame','wheel','pedal']
def __init__(self):
self.other = 'basket'
def use(self,times): ##times為次數(shù),假設(shè)使用一次騎行5km
print('You ride {}km'.format(times*5))
class Share_bike(Bike):
def cost(self,hour): ##假設(shè)一小時(shí)收取2元
print('You spent {}'.format(hour*2))
mybike = Share_bike()
print(mybike.other)
mybike.use(2)
mybike.cost(3)
結(jié)果:
basket
You ride 10km
You spent 6