day25-python-spider
day25-python-spider
python
抓取动态加载数据
代码
# 动态爬取数据实战
from fake_useragent import UserAgent
import requests
import xlwt
# 请求的url
url = "https://movie.douban.com/j/new_search_subjects"
# 伪装请求头
ua = UserAgent()
headers = {
"User-Agent": ua.firefox
}
# 当前页
pageNum = 1
start = str((pageNum - 1) * 20)
params = {
"sort": "U",
"range": "0,10",
"tags": "动漫",
"start": "20",
}
# 获取响应对象
resp = requests.get(url=url, headers=headers, params=params)
# 获取页面信息
html = resp.json()
dataList = html["data"]
# 保存数据到excel表格中
book = xlwt.Workbook()
sheet1 = book.add_sheet("电影名单", cell_overwrite_ok=True)
head = ['directors', 'rate', 'cover_x', 'star', 'title', 'url', 'casts', 'cover', 'id', 'cover_y']
for i in range(0, len(head)):
sheet1.write(0, i, head[i])
i = 0 # 控制行
j = 0 # 控制列
for data in dataList:
j = 0 # 每次重置j=0
i = i + 1
for key, value in data.items():
sheet1.write(i, j, value)
j = j + 1
book.save("电影.xls")
for data in dataList:
print(data)

json模块
json介绍
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,遵循欧洲计算机协会指定的JavaScript规范。
数据格式:
jsonstr={"key":"value","key1":"value1",...}
作用
完成json与python两种数据格式的相互转换
常用方法
json.loads()
将json格式的字符串转换称python对象(列表、字典、元组、整型以及浮点型)
# json模块
import json
# web 的json串
websiteInfo='{"name":"yaya","age":"18","sex":"male"}'
print(type(websiteInfo))
pyDict=json.loads(websiteInfo)
print(pyDict)
print(type(pyDict))

json.dumps()
将python对象转换为json字符串
# 字典
dict={"name":"丫丫","age":"18","sex":"女","data":[{"hello":"world"}]}
obj=json.dumps(dict,ensure_ascii=False) # ensurr_ascii 防止中文乱码
print(type(obj))
print(obj)

可以将python对象(字典、列表)转换为json字符串,并将转化后的数据写入到json格式的文件中,因此放方法必须操作文件流对象。
作用:将爬取的数据以json格式保存到文件中
json.dump(object,f,indent=0,ensure_ascii=False)
参数说明:
object:python数据对象,比如字典,列表等
f:文件流对象,即文件句柄
indent:格式化存储数据,使json字符串更容易读
ensure_ascii:是否使用ascii编码,当数据中出现中文的时候,需要将其设置为False
- 字典
# 字典
dict={"name":"丫丫","age":"18","sex":"女","data":[{"hello":"world"}]}
with open(file="web.json",mode="w",encoding="utf-8") as f:
json.dump(obj=dict,fp=f,indent=0,ensure_ascii=False)

- 列表
# 列表
pyList=["name","age","sex"]
with open(file="web.json",mode="w",encoding="utf-8") as f:
json.dump(obj=pyList,fp=f,indent=0,ensure_ascii=False)

json.load()
该方法用于操作文件流对象,标识从json文件中读取JSON字符串,
并将读取内容转换为Python对象
load(file)
file 文件对象
- 范例
# 字典
dict={"name":"丫丫","age":"18","sex":"女","data":[{"hello":"world"}]}
pyList=["name","age","sex"]
with open(file="web.json",mode="w",encoding="utf-8") as f:
json.dump(obj=dict,fp=f,indent=0,ensure_ascii=False)
with open(file="web.json",mode="r",encoding="utf-8") as f:
obj=json.load(f)
print(type(obj))
print(obj)

总结
| 方法 | 作用 |
|---|---|
| json.dumps() | 将python对象转换称json字符串 |
| json.loads() | 将json字符串转换成python对象 |
| json.dump() | 将python中的对象转换成json字符串存储到文件中 |
| json.load() | 将文件中的json字符串转化成python对象提取出来 |
其他
遍历字典
dict={}
for key,value in dict.items():
print(key,value)
for key in dict.keys():
print(key)
for value in dict.values():
print(value)

浙公网安备 33010602011771号