Python 数据抓取(二)

博主笔记,无任何使用教程。

文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#引入requests模块
import requests
#定义get_content函数
def get_content(url):
resp = requests.get(url)
return resp.text
if __name__ == '__main__':
#定义url,值为要抓取的目标网站网址
url = "https://www.yoosen.top"
#调用函数返回值赋值给content
content = get_content(url)
#打印输出content的前50个字符
print("前50个字符为:", content[0,50])
#得到content的长度
content_len = len(content)
print("内容的长度为:", content_len)
#判断内容长度是否大于40KB
if content_len >= 40*1024:
print("内容的长度大于等于40KB.")
else:
print("内容的长度小于40KB.")
#方式1
#文件的写入
print('-' * 20)
print('方式1:','文件写入')
#传统文件操作方式:文件名home_page.html,打开模式w,即写入操作,a模式为追加
f1 = open('home_page.html','w',encoding = 'utf8')
f1.write(content)
f1.close()
#文件的读取
print('方式1:','文件读取')
f2 = open('home_page.html','r',encoding = 'utf8')
content_read = f2.read()
print("方式1读取的前50个字符为:", content_read[0:50])
#close在文件对象使用完毕后关闭
f2.close()
#方式2
#文件的写入
print('-' * 20)
print('方式2:','文件写入')
with open('home_page_2.html', 'w', encoding = 'utf8') as f3:
f3.write(content)
#文件的读取
with open('home_page_2.html', 'r', encoding = 'utf8') as f4:
content_read_2 = f4.read()
print("方式2读取的前50个字符为:", content_read_2[0:50])

循环

Python支持while和for循环

while循环

1
2
3
4
5
6
7
8
9
10
>>>x=0
>>>while x<5:
... print(x, "<5")
... x += 1
...
0 <5
1 <5
2 <5
3 <5
4 <5

for循环

1
2
3
4
5
6
7
8
>>> for x in range(0, 5):
... print(x, "<5")
...
0 <5
1 <5
2 <5
3 <5
4 <5

多重循环

1
2
3
4
5
6
7
8
9
10
>>> for i in range(0, 3):
for j in range(0, 2):
print("i=", i, "j=", j)
i= 0 j= 0
i= 0 j= 1
i= 1 j= 0
i= 1 j= 1
i= 2 j= 0
i= 2 j= 1

异常

try…except 相关链接:Python 异常处理

python标准异常

异常名称 描述
BaseException 所有异常的基类
SystemExit 解释器请求退出
KeyboardInterrupt 用户中断执行(通常是输入^C)
Exception 常规错误的基类
StopIteration 迭代器没有更多的值
GeneratorExit 生成器(generator)发生异常来通知退出
StandardError 所有的内建标准异常的基类
ArithmeticError 所有数值计算错误的基类
FloatingPointError 浮点计算错误
OverflowError 数值运算超出最大限制
ZeroDivisionError 除(或取模)零 (所有数据类型)
AssertionError 断言语句失败
AttributeError 对象没有这个属性
EOFError 没有内建输入,到达EOF 标记
EnvironmentError 操作系统错误的基类
IOError 输入/输出操作失败
OSError 操作系统错误
WindowsError 系统调用失败
ImportError 导入模块/对象失败
LookupError 无效数据查询的基类
IndexError 序列中没有此索引(index)
KeyError 映射中没有这个键
MemoryError 内存溢出错误(对于Python 解释器不是致命的)
NameError 未声明/初始化对象 (没有属性)
UnboundLocalError 访问未初始化的本地变量
ReferenceError 弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError 一般的运行时错误
NotImplementedError 尚未实现的方法
SyntaxError Python 语法错误
IndentationError 缩进错误
TabError Tab 和空格混用
SystemError 一般的解释器系统错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
UnicodeError Unicode 相关的错误
UnicodeDecodeError Unicode 解码时的错误
UnicodeEncodeError Unicode 编码时错误
UnicodeTranslateError Unicode 转换时错误
Warning 警告的基类
DeprecationWarning 关于被弃用的特征的警告
FutureWarning 关于构造将来语义会有改变的警告
OverflowWarning 旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning 关于特性将会被废弃的警告
RuntimeWarning 可疑的运行时行为(runtime behavior)的警告
SyntaxWarning 可疑的语法的警告
UserWarning 用户代码生成的警告

元组

定义元组时使用“,”或“()

1
2
3
4
5
6
7
8
>>> t1=1,2,3 #元组的打包(packing),反之为解包(unpacking)
>>> t1
(1,2,3)
>>> t2=(1,2,3)
>>> t2
(1,2,3)
>>> t1=t2
True

元组不可变,列表可变

1
2
3
4
5
6
7
>>> t1[0]
1
>>> t1[0]=4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>

当某一元素是可变类型时,可以修改该元素

1
2
3
4
5
6
7
8
>>> t3=(1,2,[3,4])
>>> t3[2][1]=5
>>> t3
(1, 2, [3, 5])
>>> t3[2]=[3,5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

列表

(1)可使用“[]”定义列表,列表元素从0开始,越界出现错误,len可以获得列表长度

1
2
3
4
5
6
7
8
9
10
11
12
>>> l1=[1, 2, 3, 'abc']
>>> l1[0]
1
>>> l1[3]
'abc'
>>> l1[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> len(l1)
4
>>>

(2)支持索引(l1[1:3])和切片
(3)列表元素可变,可利用索引修改元素

1
2
3
4
5
6
7
8
>>> l1
[1, 2, 3, 'abc']
>>> l1[2]
3
>>> l1[2]=5
>>> l1
[1, 2, 5, 'abc']
>>>

(4)append 向列表末尾追加新元素
extend 向末尾追加序列(元组或列表)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> l1
[1, 2, 5, 'abc']
>>> l1.append('def')
>>> l1
[1, 2, 5, 'abc', 'def']
>>> l1.append(['def'])
>>> l1
[1, 2, 5, 'abc', 'def', ['def']]
>>> l1.append(['def',''456'])
File "<stdin>", line 1
l1.append(['def',''456'])
^
SyntaxError: invalid syntax
>>> l1.append(['def','456'])
>>> l1
[1, 2, 5, 'abc', 'def', ['def'], ['def', '456']]
>>> l1.extend('dgj','789')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: extend() takes exactly one argument (2 given)
>>> l1.extend(['ghj','789'])
>>> l1
[1, 2, 5, 'abc', 'def', ['def'], ['def', '456'], 'ghj', '789']

(5)列表支持instert、remove、pop等方法操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> l2=['a','b','c']
#指定位置插入一个元素,该索引位置原先元素和其后元素都会响应向后地索引值加1
#索引超出边界,则取最右端后面或最左端元素前面插入
>>> l2.insert(1,'x')
>>> l2
['a', 'x', 'b', 'c']
>>> l2.insert(1,'b')
>>> l2
['a', 'b', 'x', 'b', 'c']
#若传递给remove的元素列表有重复,则删除第一个
>>> l2.remove('b')
>>> l2
['a', 'x', 'b', 'c']
#pop从列表中弹出一个元素,默认弹出末尾元素
>>> p1=l2.pop()
>>> p1
'c'
>>> l2
['a', 'x', 'b']
>>> p2=l2.pop(1)
>>> p2
'x'
>>> l2
['a', 'b']
#del删除指定位置元素
>>> del l2[1]
>>> l2
['a']
>>>

(6)列表排序有sort(),或sorted

1
2
3
4
5
6
7
8
9
10
>>> l3=[2,1,5,7]
>>> l3
[2, 1, 5, 7]
>>> l3.sort()#默认升序
>>> l3
[1, 2, 5, 7]
>>> l3.sort(reverse=True)#向sort传入reverse=True会按逆序排序
>>> l3
[7, 5, 2, 1]
>>>

除reverse外,sort还有key参数

1
2
3
4
5
6
7
8
9
10
11
12
>>> x=['hello','abc','1234']
>>> x.sort()
>>> x
['1234', 'abc', 'hello']
>>> x.sort(key=len)
>>> x
['abc', '1234', 'hello']
>>> x=['hello','abc','1234']
>>> x.sort(key=lambda elem:len(elem))
>>> x
['abc', '1234', 'hello']
>>>

key = lambda elem:len(elem)

其中,lambda elem:len(elem)就是lambda算子。它表示一个函数。这个函数接受一个参数,参数名为elem。参数名可以是符合命名规则的任意名称。冒号后面是函数体,表示函数执行的动作。其含义是在进行列表元素的比较时,比较的依据是将各元素分别传入key代表的lambda算子,然后根据算子的执行结果作为比较的依据。这与key=len的效果是一样的。

(7)列表推导

1
2
3
4
>>> l = [x for x in range(1,101) if x%2==0]
>>> l
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
>>>

未完待续。。。

本文标题:Python 数据抓取(二)

文章作者:Yoosen

发布时间:2017年10月11日 - 15:10

最后更新:2017年10月18日 - 10:10

原始链接:http://www.yoosen.top/2017/10/11/Python-数据抓取(二)/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%