python爬虫(三)之虎嗅网汽车文章爬虫

python爬虫(三)之虎嗅网汽车文章爬虫

闲来没事,闲鱼上有个好兄弟要我从虎嗅网上抓一些汽车文章的爬虫,于是大力出奇迹,我写了一个python程序,将这个网站上所有的汽车文章全部抓取下来了,存储到了本地的虎嗅.csv

import requests
import json
import csv
from lxml import etree
import time
import random
from datetime import datetime


class Huxiu:

    def __init__(self):
        self.article_list_pre_url = "https://api-article.huxiu.com/web/channel/articleList"
        self.article_list_post_url = "&pageSize=10&orderBy=createTime&order=DESC&isProfessional=true&userType=0"
        self.start_page = 1
        self.end_page = 1000
        self.article_list_headers = {
            'authority': 'api-article.huxiu.com',
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'content-type': 'application/x-www-form-urlencoded',
            'cookie': 'Hm_lvt_502e601588875750790bbe57346e972b=1710422257; huxiu_analyzer_wcy_id=9wau9zilte4pu8mg6b7z; hx_object_visit_referer_1_2702514=https%3A%2F%2Fwww.huxiu.com%2Fchannel%2F21.html; Hm_lpvt_502e601588875750790bbe57346e972b=1710422520',
            'origin': 'https://www.huxiu.com',
            'referer': 'https://www.huxiu.com/',
            'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
        }

        self.article_detail_headers = {
            'authority': 'www.huxiu.com',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'max-age=0',
            'cookie': 'Hm_lvt_502e601588875750790bbe57346e972b=1710422257; huxiu_analyzer_wcy_id=9wau9zilte4pu8mg6b7z; Hm_lpvt_502e601588875750790bbe57346e972b=1710422520',
            'referer': 'https://www.huxiu.com/channel/21.html',
            'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
        }

    def post_request(self, url, headers, payload):
        response = requests.request("POST", url, headers=headers, data=payload)
        return response.text

    def get_request(self, url, headers):
        response = requests.request("GET", url, headers=headers)
        return response.text

    def do_work(self):
        with open('虎嗅.csv', 'w', newline='', encoding='utf-8-sig') as file:
            writer = csv.writer(file)
            csv_title = ["标题", "作者", "发布时间", "原文地址", "正文"]
            writer.writerow(csv_title)

            page_no = 1
            last_time = 1710425737
            # 最早的时间戳 1684505520
            while True:
                print("=====================> 当前第" + str(page_no) + "页 =======================")
                payload = 'platform=www&last_time=' + str(last_time) + '&channel_id=21'
                print(datetime.fromtimestamp(last_time).strftime('%Y-%m-%d %H:%M:%S'))
                text = self.post_request(self.article_list_pre_url, headers=self.article_list_headers, payload=payload)
                json_data = json.loads(text)
                data = json_data["data"]["datalist"]
                if len(data) <= 0:
                    break
                self.write_page(writer, data)
                last_time = int(json_data["data"]["last_time"])
                page_no += 1

    def write_page(self, writer, data):
        for item in data:
            # print(item["title"])
            # print(item["author"]["username"])
            # print(item["created_at"])
            # 获取文章详情内容
            # https://www.xchuxing.com/article/116378
            article_url = "https://www.huxiu.com/article/" + str(item["aid"]) + ".html"
            text = self.get_request(article_url, headers=self.article_detail_headers)

            html = etree.HTML(text)
            # //*[@id="nice"]/div/div[1]
            result = html.xpath('normalize-space(//*[@id="article-content"])')
            # time_struct = time.localtime(item["created_at"])
            # date = time.strftime("%Y-%m-%d %H:%M:%S", time_struct)

            row = [item["title"], item["user_info"]["username"], article_url, item["formatDate"], result]
            writer.writerow(row)
            # seconds = random.randint(1, 4)
            print("===========> 当前文章 " + article_url + " 写入完毕")
            # print("===========> 当前文章 " + article_url + " 写入完毕,等待" + str(seconds) + "秒继续")
            # time.sleep(seconds)


if __name__ == '__main__':
    huxiu = Huxiu()
    huxiu.do_work()

下面是程序的运行结果,最终的数据存储在同级目录下的虎嗅.csv文件中

image-20240506221436415

写在最后

代码精选(www.codehuber.com),程序员的终身学习网站已上线!

如果这篇【文章】有帮助到你,希望可以给【JavaGPT】点个赞👍,创作不易,如果有对【后端技术】、【前端领域】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 【JavaGPT】❤️❤️❤️,我将会给你带来巨大的【收获与惊喜】💝💝💝!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/612334.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

(三十九)第 6 章 树和二叉树(二叉树的三叉链表存储)

1. 背景说明 2. 示例代码 1) errorRecord.h // 记录错误宏定义头文件#ifndef ERROR_RECORD_H #define ERROR_RECORD_H#include <stdio.h> #include <string.h> #include <stdint.h>// 从文件路径中提取文件名 #define FILE_NAME(X) strrchr(X, \\) ? strrc…

RF Plasma gernerator-系列(RF-5KW Adtec)说明书TX06-9001-00

RF Plasma gernerator-系列(RF-5KW Adtec)说明书TX06-9001-00

C++随手写一个打字练习软件TL(TypeLetters)附原码

C随手写一个打字练习软件TL&#xff08;TypeLetters&#xff09;附原码 说明 软件名称&#xff1a;TL&#xff08;TypeLetters&#xff09; 开发语言&#xff1a;C 适合人群&#xff1a;零基础小白或C学习者 软件功能&#xff1a;打字练习软件TL&#xff08;TypeLetters&#…

【树莓派4B】如何用树莓派的串口发送数据给单片机

文章目录 查看路由器中的树莓派IProot连接打开vnc远程桌面服务打开win的远程桌面软件输入IP和端口串口发送数据硬件连接树莓派发送 查看路由器中的树莓派IP root连接 打开vnc远程桌面服务 vncserver :1打开win的远程桌面软件 输入IP和端口 192.168.3.33:1输入密码qwer1234后点…

2019年计算机真题

2019年计算机真题 离散数学 一、用逻辑符号表达下列语句(论域为包含一切事物的集合) 1&#xff09;过平面上的两个点&#xff0c;有且仅有一条直线通过。 解: (1) P ( x , y ) : x , y \mathrm{P}_{(\mathrm{x}, \mathrm{y})}: \mathrm{x}, \mathrm{y} P(x,y)​:x,y 是平面上的…

Vitis HLS 学习笔记--理解串流Stream(3)

目录 1. 简介 2. 综合报告的差别 2.1 包含 do-while 2.2 不包含 do-while 2.3 报告差异分析 3. 总结 1. 简介 针对《Vitis HLS 学习笔记--理解串流Stream(2)-CSDN博客》博文的内容&#xff0c;做进一步说明。 2. 综合报告的差别 2.1 包含 do-while Performance & …

QML及VTK配合构建类MVVM模式DEMO

1 创建QT QUICK项目 这次我们不在主程中加载VTK的几何&#xff1b; 在qml建立的控件&#xff0c;创建MyVtkObject类的单例&#xff0c;main中将指针和单例挂钩&#xff1b; 在MyVtkObject实例中操作 QQuickVTKRenderItem 类即可&#xff1b; 由于VTK的opengl显示是状态机&a…

脆皮之“指针和数组的关系”

文章目录 1. 数组名的理解2. 使用指针访问数组3. 一维数组传参的本质4. 冒泡排序5. 二级指针6. 指针数组7. 指针数组模拟二维数组 hello&#xff0c;大家好呀&#xff0c;窝是脆皮炸鸡。这一期是关于数组和指针的&#xff0c;我觉得并不是很难&#xff0c;但是我觉着下一期可能…

最新版Ceph( Reef版本)块存储简单对接k8s

当前ceph 你的ceph集群上执行 1.创建名为k8s-rbd 的存储池 ceph osd pool create k8s-rbd 64 642.初始化 rbd pool init k8s-rbd3 创建k8s访问块设备的认证用户 ceph auth get-or-create client.kubernetes mon profile rbd osd profile rbd poolk8s-rbd部署 ceph-rbd-csi c…

如何用 OceanBase做业务开发——【DBA从入门到实践】第六期

当应用一款新的数据库时&#xff0c;除了基础的安装部署步骤&#xff0c;掌握其应用开发方法才是实现数据库价值的关键。为此&#xff0c;我们特别安排了5月15日&#xff08;周三&#xff09;的《DBA 从入门到实践》第六期课程——本次课程将带大家了解OceanBase数据库的开发流…

学习Java的日子 Day45 HTML常用的标签

Day45 HTML 1.掌握常用的标签 1.1 标题标签 h1-h6 <h1>一级标签</h1> <h2>二级标签</h2> <h3>三级标签</h3> <h4>四级标签</h4> <h5>五级标签</h5> <h6>六级标签</h6> 显示特点&#xff1a; * 文字…

论文解读--------FedMut: Generalized Federated Learning via Stochastic Mutation

动机 Many previous works observed that the well-generalized solutions are located in flat areas rather than sharp areas of the loss landscapes. 通常&#xff0c;由于每个本地模型的任务是相同的&#xff0c;因此每个客户端的损失情况仍然相似。直观上&#xff0c;…

鸿蒙内核源码分析(文件句柄篇) | 你为什么叫句柄

句柄 | handle int open(const char* pathname,int flags); ssize_t read(int fd, void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count); int close(int fd);只要写过应用程序代码操作过文件不会陌生这几个函数,文件操作的几个关键步骤嘛,跟把大…

react18【实战】tab切换,纯前端列表排序(含 lodash 和 classnames 的安装和使用)

技术要点 动态样式 className{tabItem ${currentType item.value && "active"}}安装 lodash npm i --save lodash使用 lodash 对对象数组排序&#xff08;不会改变源数组&#xff09; _.orderBy(dataList, "readNum", "desc")src\De…

WireShark对tcp通信数据的抓包

一、抓包准备工作 安装wireshark sudo apt update sudo apt install wireshark 运行 二、WireShark工具面板分析 上图中所显示的信息从上到下分布在 3 个面板中&#xff0c;每个面板包含的信息含义如下&#xff1a; Packet List 面板&#xff1a;显示 Wireshark 捕获到的所…

【项目实战】使用Github pages、Hexo如何10分钟内快速生成个人博客网站

文章目录 一.准备工作1.安装git2.安装node安装 cnpm 3.使用 GitHub 创建仓库&#xff0c;并配置 GitHub Pages0.Github Pages是什么1. 在 GitHub 上创建一个新仓库2. 创建您的静态网站3. 启用 GitHub Pages4. 等待构建完成5. 访问您的网站 二. Hexo1.什么是Hexo2.安装Hexo1. 安…

【核武器】2024 年美国核武器-20240507

2024年5月7日,《原子科学家公报》发布了最新版的2024美国核武器手册 Hans M. Kristensen, Matt Korda, Eliana Johns, and Mackenzie Knight, United States nuclear weapons, 2024, Bulletin of the Atomic Scientists, 80:3, 182-208, DOI: https://doi.org/10.1080/00963…

Vue面试经验2

Vue 你说你在vue项目中实现了自定义指令&#xff0c;如何实现 全局指令在main.js入口文件中实现 使用方法&#xff1a;v-指令名称 每个钩子函数都有两个参数&#xff08;ele,obj&#xff09; ele:绑定指令的元素 obj:指令的一些信息&#xff08;比如绑定指令的值&#xff0c…

OpenCV中的模块:点云配准

点云配准是点云相关的经典应用之一。配准的目的是估计两个点云之间位姿关系从而完成两者对应点之间的对齐/对应,因而在英文中又叫“align”、“correspondence”。笔者曾经是基于OpenCV进行三维重建的,并且从事过基于深度学习的6DoF位置估计等工作。在这些工作中,除了重建点…

docker compose kafka集群部署

kafka集群部署 目录 部署zookeeper准备工作2、部署kafka准备工作3、编辑docker-compose.yml文件4、启动服务5、测试kafka6、web监控管理 部署zookeeper准备工作 mkdir data/zookeeper-{1,2,3}/{data,datalog,logs,conf} -p cat >data/zookeeper-1/conf/zoo.cfg<<EOF…