python爬虫 - 爬取html中的script数据(36kr.com新闻信息)

文章目录

  • [1. 分析页面内容数据格式](#1. 分析页面内容数据格式)
  • [2. 使用re.findall方法,爬取新闻](#2. 使用re.findall方法,爬取新闻)
  • [3. 使用re.search 方法,爬取新闻](#3. 使用re.search 方法,爬取新闻)

1. 分析页面内容数据格式

  • 打开 https://36kr.com/

  • 按F12(或 在网页上右键 --> 检查(Inspect))

  • 找到网页上的Network(网络)部分

  • 鼠标点击网页页面,按 Ctrl + R 刷新网页页面,可以看到 NetWork(网络)部分会刷新出很多的网络信息

  • 在Name 列,找到 36kr.com 条目,右侧自动显示网页的相关内容:Headers, Preview, Response ... ...

  • 分析Response内容,所需要关心的内容,位于整个html页面的下面

2. 使用re.findall方法,爬取新闻

要点:从 之间的数据都是json数据。 json.loads会自动将false转为False, true转为True

复制代码
import re
import requests
import json


# URL路径
url = "https://36kr.com/"
response = requests.get(url)
str1 = response.content.decode()

# 查找,使用正在表达式->取数组的第一个
result = re.findall("<script>window.initialState=(.*?)</script>", str1)[0]

# 先写入到本地,再查看
with open("36kr.json", "w", encoding="utf-8") as f:
    f.write(result)
    
# 加载json转换成python类型
json_result = json.loads(result)
print(json_result)


# pretty print the data: 其中 json.dumps() 对数据格式进行了美化:
print(json.dumps(json_result, indent=4))

print(f'data.theme        = {json_result["theme"]}')
print(f'data.isSpider     = {json_result["isSpider"]}')

for item in json_result["channel"]:
    print(f'name = {item["name"]}, '
          f'key = {item["key"]} ')

运行结果:


3. 使用re.search 方法,爬取新闻

要点:从 之间的数据都是json数据。 json.loads会自动将false转为False, true转为True

复制代码
import re
import json
import requests


# URL路径
url = "https://36kr.com/"
html_doc = requests.get(url).text


data = re.search(r"<script>window.initialState=(.*?)</script>", html_doc)
print(f"data = {data}")

json_result = json.loads(data.group(1))
print(f"json_data = {json_result}")

# pretty print the data:
print(f"json_dump = {json.dumps(json_result, indent=4)}")

print(f'data.theme        = {json_result["theme"]}')
print(f'data.isSpider     = {json_result["isSpider"]}')

for item in json_result["channel"]:
    print(f'name = {item["name"]}, '
          f'key = {item["key"]} ')

运行结果:


相关推荐
程序员龙叔4 小时前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780517 小时前
使用 Python 操作 Word 内容控件
后端·python
码云骑士8 小时前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python
隔窗听雨眠9 小时前
大模型加爬虫上篇:技术融合与架构革新
爬虫·架构
闵孚龙9 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
goldenrolan9 小时前
A公司物料替代测试系统 v1.7:从需求到 exe/apk 的 AI 辅助全链路实践
android·自动化测试·软件测试·python·ai
菜板春9 小时前
jupyter入门-手册-特征探索
python·jupyter
Metaphor6929 小时前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
极光代码工作室9 小时前
基于数据仓库的电商数据分析平台
大数据·hadoop·python·spark·数据可视化