本地数据获取
文文件的打开,读写和关闭件
- 打开后才能进行读写
- 为什么需要关闭?
因为Python可能会缓存写入的数据 如果程序异常崩溃了 数据就不能写入到文件中 所以为了安全起见 文件用完以后要养成 主动关闭文件的习
文件的打开
file_obj = open(filename, mode='r', buffering=-1)
- mode为可选参数,默认值为r
- buffering也为可选参数,默认值为-1(0代表不缓冲,1或大于1的值表示缓冲一行或指定缓冲区大小)
- 在Python中 二进制文件可以不使用缓冲
- 文本文件必须要使用缓冲
- open()函数-mode
- 返回值
- open()函数返回一个文件(file)对象
- 文件对象可迭代
文件相关函数
>>> f = open('firstpro.txt', 'w')
>>> f.write('Hello, World!')
>>> f.close()
with open(‘firstpro.txt’, ‘w’) as f:
f.write()
- f.read()
- file_obj.read(size)
- file_obj.read()
- 注意文件指针的概念,可以用f.tell() 查看
- f.readlines()
- readlines返回一个列表 Python中不删除换行符,需要程序员自己完成
f = open(r'companies.txt')
cNames = f.readlines()
print cNames
f.close()
Output:
['GOOGLE Inc.\n', 'Microsoft Corporation\n', 'Apple Inc.\n', 'Facebook, Inc.']
- f.seek(offset , whence=0)
− 在文件中移动文件指针,从 whence(0表示文件头部,1表示 当前位置,2表示文件尾部)偏 移offset个字节
– whence参数可选,默认值为0
网络数据获取
获取过程
- 抓取
- urllib内建模块
- urllib.request : 已经逐渐被Request第三方库替代
- Requests第三方库:适合中小型网络爬虫的开发
- Scrapy框架:大型
- 解析
Requests库
>>> import requests
>>> r = requests.get('https://book.douban.com/subject/1084336/comments/')
>>> r.status_code
200
>>> print(r.text)
- 解码
- json格式
- 二进制格式
- re.text
- re.encoding = ‘utf-8’
- 遵循网站爬虫协议 robots.txt
- 例如 www.douban.com/robots.txt
BeautifulSoup
- 常用解析器
- BeautifulSoup对象
- Tag : HTML,XML中的标签,大多数BeautifulSou对象都是Tag
- NavigableString
- BeautifulSoup
- Comment : NavigableString的子类
- 例子
from bs4 import BeautifulSoup
markup = '<p class="title"><b>The little Prince</b></p>'
soup = BeautifulSoup(markup, 'lxml')
print(soup.text)
The little Prince
type(soup.b)
Out[5]: bs4.element.Tag
soup.b
Out[6]: <b>The little Prince</b>
tag = soup.p
tag.name
Out[8]: 'p'
tag.attrs
Out[9]: {'class': ['title']}
tag['class']
Out[10]: ['title']
tag.string
Out[11]: 'The little Prince'
type(tag.string)
Out[12]: bs4.element.NavigableString
soup.find_all('b')
Out[13]: [<b>The little Prince</b>]
正则表达式
数据表示
序列
- 成员
- 访问模式
- 元素从0开始通过下标偏移量访问
- 一次可访问一个或多个元素
- 操作
值比较: < > <= >= == !=
布尔运算: not and or
对象身份比较: is is not
- 序列类型运算符
> 获取,重复,连接,判断
- 内减函数运算符
序列类型转换内建函数: list() str() tuple()
>>> list('Hello, World!')
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
>>> tuple("Hello, World!")
('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')
序列类型可用内建函数
enumerate()
reversed()
len()
sorted()
max()
sum()
min()
zip()
字符串
- 输出形式
- format_string % (arguments_to_convert)
- format_string.format(arguments_to_convert)
列表
- 可扩展的容器对象
- 包含不同类型对象
- 列表方法
- append()
- copy()
- count()
- extend()
- index()
- insert()
- pop()
- remove()
- reverse()
- sort()
- 列表解析
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x ** 2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x ** 2 for x in range(10) if x ** 2 < 50]
[0, 1, 4, 9, 16, 25, 36, 49]
>>> [(x+1, y+1) for x in range(2) for y in range(2)]
[(1, 1), (1, 2), (2, 1), (2,