Python爬虫

一. Python爬虫基础

2018-02-14  本文已影响0人  橄榄的世界

1.字符串基础

①字符串的加法和乘法

a = 'I'
b = ' love'
c = ' Scrapy'
d = '!'
print(a + b + c + d*3)

结果: I love Scrapy!!!

②字符串的切片和索引

a = 'I love Scrapy!!!'
print(a[0],a[0:6],a[-1])

结果: I I love !

③字符串方法

a = " www..baidu..com "
link = a.strip().replace("..",".").split(".")
print(link)

分析: www..baidu..comwww.baidu.com['www', 'baidu', 'com']
结果: ['www', 'baidu', 'com']

2.函数与控制语句

①函数

def func(参数1,参数2...):
    return 结果    

②判断语句

if...else...
if...elif...else...    #多重条件

③循环语句

for item in iterable:   #方式一
    pass

for i in range(1:10):  #方式二
    print(i)

while 条件:           #方式三
    执行语句

3.Python数据结构

①列表:爬虫实战中使用最多的数据结构。例如构造多个URL,保存爬取到的数据等。

names = ["张三","李四","王五"]
ages = [6,7,8]
for name,age in zip(names,ages):
    print(name,age,end='| ')

结果: 张三 6|李四 7|王五 8|

urls = ['http://www.top123.com/{}-8'.format(i) for i in range(1,5)]
for url in urls:
    print(url)

结果:

http://www.top123.com/1-8
http://www.top123.com/2-8
http://www.top123.com/3-8
http://www.top123.com/4-8

②字典:搭配数据库使用,此处仅列出字典的创建。

users_info = {'张三': 6, '李四': 7, '王五': 8}

③元组和集合:元组和集合较少使用。

其中,集合的元素无序,且无重复对象,可用于去除重复对象

list1 = ['I','You','I']
set1 = set(list1)
print(set1)

结果: {'I', 'You'}

4.Python文件操作

f = open("F:/d.txt",'w+')
f.write("Hello!")
content = f.read()
print(content)
f.close()

此时打印无结果,因为写入的数据还保存在缓存中,直至执行完f.close()。
更推荐下面的写法:

with open("F:/d.txt",'r+') as f:
    content = f.read()
    print(content)
    f.close()
描述
'r' 读模式
'w' 写模式
'a' 追加模式
'b' 二进制模式,用于图片、视频等,例如'wb'可用于下载视频。
'+' 读/写模式,可与其他模式叠加,例如'a+','wb+'等。

5.Python面向对象

①定义类:类名首字母一般大写。 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为次数,假设使用一次骑行5km
        print('You ride {}km'.format(times*5))

class Share_bike(Bike):

    def cost(self,hour):    ##假设一小时收取2元
        print('You spent {}'.format(hour*2))
        
mybike = Share_bike()
print(mybike.other)
mybike.use(2)
mybike.cost(3)

结果:

basket
You ride 10km
You spent 6
上一篇 下一篇

猜你喜欢

热点阅读