day16-简单网页数据爬取
1、练习
"""
将100以内的素数输出到一个文件中
"""
def is_prime(num:int)->bool:
"""
判断一个正整数是不是素数
:param num: 正整数
:return: 素数返回True,否则返回False
"""
for i in range(2,int(num**0.5)+1):
if num % i == 0:
return False
return True
with open('prime.txt','w') as file:
for n in range(2, 100):
if is_prime(n):
file.write(f'{n}\n')
2、对象的序列化和反序列化
"""
对象的序列化(serialization)和反序列化(deserialization)
序列化:把一个对象(字典,列表等)变成字符串(str)或者字节串(bytes二进制)
反序列化:从字节串或者字符串中还原出一个对象(字典,列表等)
python的标准库有一个名为json/pickle的模块,可以支持我们做序列化和反序列化的操作
JSON -->JavaScript Object Notation --> JavaScript语言创建对象的自变量语法
let person = {
name:"陈来",
age: 12,
sex: True
}
person.name
person.age
这种数据格式也非常适合在两个系统(尤其是异构的系统)传输数据(因为它是纯文本),
所有今天当我们说到JSON,更多的适合是把它当成一种数据交换格式。
python中的字典跟JSON格式非常像,所有我们可以通过将字典转成JSON格式的字符串,就可以写入文件中实现持久化
"""
import json
persons = {
'name': '陈来',
'age': 18,
'sex': False,
'friends': ['小兰','小明','小李'],
'car': {
'brand': 'QQ',
'max_speed': 120
}
}
import pickle
with open('persons.dat', 'wb') as file:
pickle.dump(persons, file=file)
3、将JSON格式数据还原成字典对象
"""
1.读取文件中的JSON格式数据还原成字典对象
import json
字符串变字典
1)json.loads(读出来的数据)->file.read()->json.loads(file.read())
2)json.load(fp=file) 从文件中读出来还原成字典
字典变字符串
1)json.dump(序列,fp=file) 写进文档里
2)json.dumps(序列(字典)) ->file.write(json.dumps(序列(字典)))
import pickle
"""
import json
with open('persons.txt') as file:
obj = json.load(fp=file)
print(obj)
print(type(obj))
"""
2.读取文件中的二进制格式数据还原成字典对象
"""
import pickle
with open('persons.dat', 'rb') as file:
content = file.read()
obj = pickle.loads(content)
print(obj, type(obj))
file.seek(0)
obj = pickle.load(file=file)
print(obj, type(obj))
4、联网获取网页数据

"""
example06 - 联网获取数据
URL ---> 网址 ---> 统一资源定位符 ---> 能够唯一标识一个(网络)资源的符号
https://www.baidu.com:443/index.html
https://14.215.177.38:443/index.html
https://www.baidu.com:443/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png
协议://用户名:口令@域名或者IP地址:端口/路径1/路径2/资源名称
URI ---> 统一资源标识符 ---> URL + URN
使用三方库 requests 可以非常方便的实现通过URL访问网络资源的操作
可以使用Python的包管理工具 pip 来安装和管理三方库以及三方工具
1、pip --version 检测版本以及是否可以用pip(Terminal中检测)
2、修改 pip 下载源为国内的镜像网站(推荐使用豆瓣网的镜像)(全局设置)
pip config set global.index-url https://pypi.doubanio.com/simple
查找三方库:pip search requests
安装三方库:pip install requests 黄色警告不用管
卸载三方库:pip uninstall requests
更新三方库:pip install -U requests
协议 ---> 规范和标准 ---> 网络协议 ---> 通过网络进行通信的双方要遵守的规范和标准
HTTP ---> 超文本传输协议 ---> 请求响应式协议
import json
import requests
resp = requests.get(
url='http://apis.juhe.cn/simpleWeather/query',
params={
'city': '上海',
'key': 'e73ebce8dc3cb2f35510f4462f08430c'
}
)
weather_dict = json.loads(resp.text)
print(weather_dict['result']['realtime'])
5、操作excel文件
"""
# pip install openpyxl 下载可以读写excel文件
# Python操作excel文件
"""
import openpyxl
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.append(('姓名', '语文', '数学', '英语'))
sheet.append(('陈来', '61', '79', '70'))
sheet.append(('小新', '62', '71', '73'))
sheet.append(('小明', '64', '72', '74'))
sheet.cell(5, 1, '张三丰')
workbook.save('学生考试成绩表.xlsx')
6、通过天行数据的API接口获取头条新闻数据

from datetime import datetime
import openpyxl
import requests
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.append(('标题', '链接', '来源'))
for page in range(1, 6):
resp = requests.get(
url='http://api.tianapi.com/topnews/index',
params={
'key': 'e8c5524dd2a365f20908ced735f8e480',
'page': page,
'num': 20
}
)
result = resp.json()
for news_dict in result['newslist']:
title, url, source = news_dict['title'], news_dict['url'], news_dict['source']
sheet.append((title, url, source))
curr = datetime.now()
workbook.save(f'头条新闻数据_{curr.year}{curr.month:0>2d}{curr.day:0>2d}.xlsx')
slist']:
title, url, source = news_dict['title'], news_dict['url'], news_dict['source']
sheet.append((title, url, source))
curr = datetime.now()
workbook.save(f'头条新闻数据_{curr.year}{curr.month:0>2d}{curr.day:0>2d}.xlsx')
|