1 本地数据获取
1.1 文件的打开:
语法
file_obj = open(filename,mode=‘r’,buffering=-1)
举例
f1 = open(‘c:\ABC.txt’)
f2 = open(‘c:\ABC.txt’,‘w’)
f3 = open(‘c:\ABC.txt’,‘wb’,0)
mode为可选参数,默认值为r;
buffering也为可选参数,默认值为-1(0代表不缓冲,1或者大于1的值表示缓冲一行或者指定缓冲区大小),二进制文件可以不使用缓冲,但是文本文件必须使用缓冲。
【mode模式如图所示】
1.2 文件的写入和读取:
语法
file_obj.write(str)
filr_obj.read(size) 从文件中至多读出size字节数据,返回一个字符串
filr_obj.read() 读文件直到文件结束,返回一个字符串
举例
with open('ABC.txt','w') as f:
f.write('ABC!')
with open('ABC.txt') as f: #with语句会关闭句柄,不需要写close
p1 = f.read(3) #读取3个字节
p2 = f.read() #读取剩下的内容
语法
file_obj.readline() 读取一行数据
file_obj.readlines() 读取多行数据
file_obj.writelines() 写入多行数据
举例
s = '123456ABC789'
with open(AAA.txt','a+') as f:
f.writelines('\n')
f.writelines(s)
f.seek(0) #这句代码一定要加,把文件指针位置挪到前面
cText = f.readlines()
print(cText)
if os.path.exists('./ABC'):
shutil.rmtree('./ABC') #递归删除文件目录
os.mkdir('./ABC')
2 网络数据获取
#抓取静态数据
import requests
r = requests.get('https://AAA.com/BBB/comments/')
r.status_code
r.text
#获取的是二进制文件,则可以借鉴如下方法保存数据
r = requests.get('https://www.baidu.com/img/123.png')
with open('123.png.png', 'wb') as fp:
fp.write(r.content)
#有些网站会对http请求的Headers的User-Agent进行检测,需将headers信息传递给get函数的headers参数
#headers可从http测试网站https://httpbin.org或浏览器的“开发者工具”获得
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11"}
re = requests.get('https://www.zhihu.com', headers = headers)
re.status_code
#解析网页内容,推荐用BeautifulSoup包
from bs4 import BeautifulSoup
example = '<p class="title"><b>AAA</b></p>'
soup = BeautifulSoup(example,"lxml")
soup.b
输出:AAA
type(soup.b)
输出:bs4.element.Tag
soup.find_all('b')
找出所有b标签的内容
参考资料:
https://www.icourse163.org/learn/NJU-1001571005?tid=1463102441&from=study#/learn/content?type=detail&id=1240380167&cid=1261816392&replay=true
慕课课程—用python玩转数据