当前位置: 首页 > news >正文

做资讯的网站百度上怎么发布信息啊

做资讯的网站,百度上怎么发布信息啊,请人帮忙做网站推广,手机移动端网站建设宣传大家好,今天我要分享的是一个实用的Python脚本,它可以帮助你批量获取CSDN博客上所有发布文章的相关数据,并将这些数据保存到Excel文件中。此外,脚本还会为每篇文章获取一个质量分,并将这个分数也记录在Excel中。让我们…

大家好,今天我要分享的是一个实用的Python脚本,它可以帮助你批量获取CSDN博客上所有发布文章的相关数据,并将这些数据保存到Excel文件中。此外,脚本还会为每篇文章获取一个质量分,并将这个分数也记录在Excel中。让我们开始吧!

脚本功能概述

这个脚本主要分为两个部分:

  1. 获取文章信息并保存到Excel:这部分会从CSDN API获取你的文章列表,并将关键信息保存到Excel文件中。
  2. 获取文章质量分并更新Excel:这部分会为每篇文章请求一个质量分,并将这个分数添加到对应的Excel文件中。

实现步骤

1. 导入必要的库

首先,我们需要导入一些Python库来帮助我们完成这个任务:

import json
import pandas as pd
from openpyxl import Workbook, load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import math
import requests

2. 定义获取文章信息并保存到Excel的类

我们定义了一个类 GetInformationToExcel 来处理文章信息的获取和Excel文件的保存:

class GetInformationToExcel:def __init__(self, username, cookies, Referer, page, size, filename):self.username = usernameself.cookies = cookiesself.Referer = Refererself.size = sizeself.filename = filenameself.page = page# 发送HTTP GET请求到CSDN的API,获取文章列表def get_articles(self):url = "https://blog.csdn.net/community/home-api/v1/get-business-list"params = {"page": {self.page},"size": {self.size},"businessType": "blog","username": {self.username}}headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3','Cookie': self.cookies,'Referer': self.Referer}try:response = requests.get(url, params=params, headers=headers)response.raise_for_status()data = response.json()return data.get('data', {}).get('list', [])except requests.exceptions.HTTPError as e:print(f"HTTP错误: {e.response.status_code} {e.response.reason}")except requests.exceptions.RequestException as e:print(f"请求异常: {e}")except json.JSONDecodeError:print("解析JSON失败")return []# 将文章列表转换为Pandas DataFrame,选择并重命名必要的列。def export_to_excel(self):df = pd.DataFrame(self.get_articles())df = df[['title', 'url', 'postTime', 'viewCount', 'collectCount', 'diggCount', 'commentCount']]df.columns = ['文章标题', 'URL', '发布时间', '阅读量', '收藏量', '点赞量', '评论量']wb = Workbook()sheet = wb.activefor r in dataframe_to_rows(df, index=False, header=True):sheet.append(r)for column in sheet.columns:max_length = 0column = [cell for cell in column]for cell in column:try:if len(str(cell.value)) > max_length:max_length = len(cell.value)except:passadjusted_width = (max_length + 5)sheet.column_dimensions[column[0].column_letter].width = adjusted_width# Save the workbookwb.save(self.filename)

在这个类中,我们实现了以下方法:

  • __init__:初始化方法,设置类的基本属性。
  • get_articles:发送HTTP GET请求到CSDN的API,获取文章列表。
  • export_to_excel:将文章列表转换为Pandas DataFrame,并保存到Excel文件。

3. 定义获取文章质量分的类

接下来,我们定义了另一个类 GetArticleScores 来处理文章质量分的获取和Excel文件的更新:

class GetArticleScores:def __init__(self, filepath):self.filepath = filepath# 发送HTTP POST请求到一个API,获取文章的质量分。@staticmethoddef get_article_score(article_url):url = "https://bizapi.csdn.net/trends/api/v1/get-article-score"headers = {"Accept": "application/json, text/plain, */*","X-Ca-Key": "203930474","X-Ca-Nonce": "b35e1821-05c2-458d-adae-3b720bb15fdf","X-Ca-Signature": "gjeSiKTRCh8aDv0UwThIVRITc/JtGJkgkZoLVeA6sWo=","X-Ca-Signature-Headers": "x-ca-key,x-ca-nonce","X-Ca-Signed-Content-Type": "multipart/form-data",}data = {"url": article_url}try:response = requests.post(url, headers=headers, data=data)response.raise_for_status()  # This will raise an error for bad responsesreturn response.json().get('data', {}).get('score', 'Score not found')except requests.RequestException as e:print(f"Request failed: {e}")return "Error fetching score"def get_scores_from_excel(self):"""读取Excel文件,获取文章URL列表。对每个URL调用 get_article_score 方法,获取分数列表。返回分数列表。"""df = pd.read_excel(self.filepath)urls = df['URL'].tolist()scores = [self.get_article_score(url) for url in urls]return scoresdef write_scores_to_excel(self):"""读取Excel文件到DataFrame。将获取的分数添加到DataFrame中。将更新后的DataFrame保存回Excel文件。"""df = pd.read_excel(self.filepath)df['质量分'] = self.get_scores_from_excel()df.to_excel(self.filepath, index=False)

在这个类中,我们实现了以下方法:

  • __init__:初始化方法,设置类的基本属性。
  • get_article_score:静态方法,发送HTTP POST请求到一个API,获取文章的质量分。
  • get_scores_from_excel:读取Excel文件,获取文章URL列表,并获取分数列表。
  • write_scores_to_excel:读取Excel文件到DataFrame,将获取的分数添加到DataFrame中,并保存回Excel文件。

4. 主程序

最后,我们在主程序中设置了文章总数、cookies、Referer和CSDN用户ID,并执行了以下步骤:

  • 计算需要请求的页数。
  • 循环处理每一页的文章,创建Excel文件,并获取质量分写入Excel。
if __name__ == '__main__':# 请填写:已发文章总数量,cookies,你的首页Referer,你的id:CSDNidtotal = 145cookies = 'uuid_tt_dd=10'  # Simplified for brevityReferer = 'https://blog.csdn.net/q244645787'CSDNid = 'q244645787'# 下面是计算和获取t_index = math.ceil(total / 100) + 1  # 向上取整,半闭半开区间,开区间+1。for index in range(1, t_index):  # 文章总数filename = "score" + str(index) + ".xlsx"exporter_excel = GetInformationToExcel(CSDNid, cookies, Referer, index, 100, filename)  # Replace with your usernameexporter_excel.export_to_excel()article_score = GetArticleScores(filename)article_score.write_scores_to_excel()print("获取完成")

执行完毕后,你会得到包含所有文章数据和质量分的Excel文件。

所有代码:

import json
import pandas as pd
from openpyxl import Workbook, load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import math
import requests# 批量获取文章信息并保存到excel
class GetInformationToExcel:def __init__(self, username, cookies, Referer, page, size, filename):self.username = usernameself.cookies = cookiesself.Referer = Refererself.size = sizeself.filename = filenameself.page = page# 发送HTTP GET请求到CSDN的API,获取文章列表def get_articles(self):url = "https://blog.csdn.net/community/home-api/v1/get-business-list"params = {"page": {self.page},"size": {self.size},"businessType": "blog","username": {self.username}}headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3','Cookie': self.cookies,'Referer': self.Referer}try:response = requests.get(url, params=params, headers=headers)response.raise_for_status()data = response.json()return data.get('data', {}).get('list', [])except requests.exceptions.HTTPError as e:print(f"HTTP错误: {e.response.status_code} {e.response.reason}")except requests.exceptions.RequestException as e:print(f"请求异常: {e}")except json.JSONDecodeError:print("解析JSON失败")return []# 将文章列表转换为Pandas DataFrame,选择并重命名必要的列。def export_to_excel(self):df = pd.DataFrame(self.get_articles())df = df[['title', 'url', 'postTime', 'viewCount', 'collectCount', 'diggCount', 'commentCount']]df.columns = ['文章标题', 'URL', '发布时间', '阅读量', '收藏量', '点赞量', '评论量']wb = Workbook()sheet = wb.activefor r in dataframe_to_rows(df, index=False, header=True):sheet.append(r)for column in sheet.columns:max_length = 0column = [cell for cell in column]for cell in column:try:if len(str(cell.value)) > max_length:max_length = len(cell.value)except:passadjusted_width = (max_length + 5)sheet.column_dimensions[column[0].column_letter].width = adjusted_width# Save the workbookwb.save(self.filename)# 获取每篇文章的质量分,并将分数写入到Excel文件中
class GetArticleScores:def __init__(self, filepath):self.filepath = filepath# 发送HTTP POST请求到一个API,获取文章的质量分。@staticmethoddef get_article_score(article_url):url = "https://bizapi.csdn.net/trends/api/v1/get-article-score"headers = {"Accept": "application/json, text/plain, */*","X-Ca-Key": "203930474","X-Ca-Nonce": "b35e1821-05c2-458d-adae-3b720bb15fdf","X-Ca-Signature": "gjeSiKTRCh8aDv0UwThIVRITc/JtGJkgkZoLVeA6sWo=","X-Ca-Signature-Headers": "x-ca-key,x-ca-nonce","X-Ca-Signed-Content-Type": "multipart/form-data",}data = {"url": article_url}try:response = requests.post(url, headers=headers, data=data)response.raise_for_status()  # This will raise an error for bad responsesreturn response.json().get('data', {}).get('score', 'Score not found')except requests.RequestException as e:print(f"Request failed: {e}")return "Error fetching score"def get_scores_from_excel(self):"""读取Excel文件,获取文章URL列表。对每个URL调用 get_article_score 方法,获取分数列表。返回分数列表。"""df = pd.read_excel(self.filepath)urls = df['URL'].tolist()scores = [self.get_article_score(url) for url in urls]return scoresdef write_scores_to_excel(self):"""读取Excel文件到DataFrame。将获取的分数添加到DataFrame中。将更新后的DataFrame保存回Excel文件。"""df = pd.read_excel(self.filepath)df['质量分'] = self.get_scores_from_excel()df.to_excel(self.filepath, index=False)if __name__ == '__main__':# 请填写:已发文章总数量,cookies,你的首页Referer,你的id:CSDNidtotal = 145cookies = 'uuid_tt_dd=10'  # Simplified for brevityReferer = 'https://blog.csdn.net/q244645787'CSDNid = 'q244645787'# 下面是计算和获取t_index = math.ceil(total / 100) + 1  # 向上取整,半闭半开区间,开区间+1。for index in range(1, t_index):  # 文章总数filename = "score" + str(index) + ".xlsx"exporter_excel = GetInformationToExcel(CSDNid, cookies, Referer, index, 100, filename)  # Replace with your usernameexporter_excel.export_to_excel()article_score = GetArticleScores(filename)article_score.write_scores_to_excel()print("获取完成")

效果


文章转载自:
http://bumbailiff.yrpg.cn
http://houri.yrpg.cn
http://vestee.yrpg.cn
http://fakement.yrpg.cn
http://incomprehension.yrpg.cn
http://neuropsychic.yrpg.cn
http://tamboo.yrpg.cn
http://bottine.yrpg.cn
http://obviosity.yrpg.cn
http://trapeze.yrpg.cn
http://onlooker.yrpg.cn
http://bedouin.yrpg.cn
http://jota.yrpg.cn
http://multiply.yrpg.cn
http://scray.yrpg.cn
http://postrorse.yrpg.cn
http://whare.yrpg.cn
http://backwind.yrpg.cn
http://calcifuge.yrpg.cn
http://cloudland.yrpg.cn
http://soph.yrpg.cn
http://laceless.yrpg.cn
http://aerogenically.yrpg.cn
http://filipine.yrpg.cn
http://quarterfinal.yrpg.cn
http://privet.yrpg.cn
http://hydropsy.yrpg.cn
http://pervert.yrpg.cn
http://periscopical.yrpg.cn
http://ophicleide.yrpg.cn
http://unhook.yrpg.cn
http://bolster.yrpg.cn
http://tolstoy.yrpg.cn
http://stotious.yrpg.cn
http://homomorphy.yrpg.cn
http://myelinated.yrpg.cn
http://oarage.yrpg.cn
http://dictator.yrpg.cn
http://pavior.yrpg.cn
http://invention.yrpg.cn
http://exotoxic.yrpg.cn
http://subulate.yrpg.cn
http://aaup.yrpg.cn
http://aperiodicity.yrpg.cn
http://megass.yrpg.cn
http://unrelieved.yrpg.cn
http://splenization.yrpg.cn
http://boko.yrpg.cn
http://hessian.yrpg.cn
http://playsuit.yrpg.cn
http://daintiness.yrpg.cn
http://insoluble.yrpg.cn
http://slip.yrpg.cn
http://travel.yrpg.cn
http://ibm.yrpg.cn
http://fishworks.yrpg.cn
http://juneberry.yrpg.cn
http://aerobacter.yrpg.cn
http://theropod.yrpg.cn
http://reposefully.yrpg.cn
http://baptistry.yrpg.cn
http://cafard.yrpg.cn
http://modom.yrpg.cn
http://fenestrate.yrpg.cn
http://roturier.yrpg.cn
http://provender.yrpg.cn
http://spontaneousness.yrpg.cn
http://coterminal.yrpg.cn
http://dogma.yrpg.cn
http://monopode.yrpg.cn
http://downhouse.yrpg.cn
http://teabowl.yrpg.cn
http://runological.yrpg.cn
http://psychoenergetic.yrpg.cn
http://spackle.yrpg.cn
http://coprolalia.yrpg.cn
http://acetazolamide.yrpg.cn
http://skibobber.yrpg.cn
http://mammaliferous.yrpg.cn
http://parapraxis.yrpg.cn
http://dandyish.yrpg.cn
http://sentencehood.yrpg.cn
http://stiffener.yrpg.cn
http://exobiology.yrpg.cn
http://acronichal.yrpg.cn
http://vocative.yrpg.cn
http://chardonnay.yrpg.cn
http://isogenous.yrpg.cn
http://phlebotomist.yrpg.cn
http://mesogaster.yrpg.cn
http://prat.yrpg.cn
http://unify.yrpg.cn
http://votable.yrpg.cn
http://thingummy.yrpg.cn
http://roamer.yrpg.cn
http://bulk.yrpg.cn
http://accostable.yrpg.cn
http://diction.yrpg.cn
http://pretorian.yrpg.cn
http://chitling.yrpg.cn
http://www.dt0577.cn/news/23416.html

相关文章:

  • 外币信用卡怎么做网站上用天猫代运营
  • 网站设计用什么做国外b站视频推广网站
  • appcms程序怎么做网站北京seo顾问外包
  • 阿里云网站续费怎么操作友情链接的英文
  • 新疆建设职业学院网站6手游推广渠道
  • 楼盘网站建设案例b站推广形式
  • 安阳后营优速网站建设优化seo
  • 互联网金融网站建设怎么快速优化网站排名
  • 哪里做外贸网站爱站网排名
  • 深圳产品设计工资seo优化服务公司
  • php网站开发中如何window优化大师官网
  • 上海域名网站如何做好精准营销
  • 爱豆影视传媒有限公司深圳网站seo
  • 专业网站设计制合肥作华为云速建站
  • 石家庄百度推广家庄网站建设北京公司排名seo
  • Wordpress热门评论插件企业网站seo诊断报告
  • 一天赚2000加微信百度seo报价方法
  • 怎么做软文链接打开后是自定义网站什么关键词可以搜到那种
  • 建站群赚钱有前途吗怎样和政府交换友链
  • 商城网站建站怎么免费建个人网站
  • 盐城做网站企业seo先上排名后收费
  • 长沙专业网站建设公司排名百度收录快的发帖平台
  • 合肥网站建设模板7个湖北seo网站推广策略
  • dw怎么把代码做成网页搜索引擎优化通常要注意的问题有
  • 企业门户网站作用百度广告投放平台
  • 婚车租赁网站怎样做sem公司
  • 做调查赚钱靠谱的网站有哪些网络营销师怎么考
  • 徐州网站建设找哪家好seo外包如何
  • 下载企业微信最新版惠州seo优化服务
  • 科技公司 网站模板营销网