用wordpress做企业网站,wordpress 登陆注册,湛江建站公司,什么是网络营销推广Helllo , 我是小恒 由于我需要腾讯云社区#xff0c;稀土掘金以及CSDN的征文活动RSS#xff0c;找了一下没发现#xff0c;所以使用GET 请求接口对网页定时进行拉取清洗#xff0c;甚至无意间做了一个简单的json格式API 最终网址:hub.liheng.work API:http://hub.liheng.wo… Helllo , 我是小恒 由于我需要腾讯云社区稀土掘金以及CSDN的征文活动RSS找了一下没发现所以使用GET 请求接口对网页定时进行拉取清洗甚至无意间做了一个简单的json格式API 最终网址:hub.liheng.work API:http://hub.liheng.work/activities.json GitHub:https://github.com/lmliheng/hub
原理
由于浏览器的同源策略产生的跨域问题使得CSDN官方URL无法被请求获取展示到前端 使用后端代码GET网页代码对其进行数据清洗并导入json文件 注意后端程序的定时任务以及日志打印 前端代码调用本地json也不存在跨域从而实现需求
代码结构
├───pyproject/
│ ├───activities.json
│ ├───htmlone.py
│ ├───index.html
│ ├───script.log后端
实现HTML转json的数据清洗以及打印日志到scripts.log文件
#作者小恒不会java
#时间2024年5月13日
#微信a13551458597
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import json
import logging
from datetime import datetimelogging.basicConfig(filenamescript.log, levellogging.INFO)
logging.info(Script started at {}.format(datetime.now()))# 获取HTML内容,这种形式是避免get请求的跨域问题
url https://bbs.csdn.net/forums/activity?spm1035.2022.3001.8781typeId745490
response requests.get(url)
html_content response.text# 使用BeautifulSoup解析HTML
soup BeautifulSoup(html_content, html.parser)activities []# 检查做到避免重复活动
posts soup.find_all(div, {class: content})
for post in posts:activity {}# 获取活动名称title_element post.find(div, {class: long-text-title})if title_element:activity[name] title_element.text.strip()# 获取活动简介desc_element post.find(div, {class: item-desc})if desc_element:activity[description] desc_element.text.strip()# 获取活动链接link_element post.find(a, hrefTrue)if link_element:activity[link] link_element[href]# 检查活动是否已存在if link in activity and not any(existing_activity[link] activity[link] for existing_activity in activities):activities.append(activity)print(activities)with open(activities.json, w, encodingutf-8) as f:json.dump(activities, f, ensure_asciiFalse, indent4)logging.info(Script finished at {}.format(datetime.now()))定时任务
我服务器系统是linux centos7 使用cron完成定时运行并通过python代码日志打印检验运行情况
检查cron服务是否正在运行
shell
sudo systemctl status cron或者ceond如果cron服务未运行请使用以下命令启动它
sudo systemctl start cron编辑crontab文件
crontab -e在打开的编辑器中添加一行以设置定时任务。例如要每天凌晨1点运行Python脚本请添加以下行
0 1 * * * /usr/bin/python /path/to/your/script.py列出当前用户的crontab条目
crontab -l日志打印检查
scripts.log
[rootiZ7xvavc793m36sybr4bw4Z hub.liheng.work]# cat scripts.log
INFO:root:Script started at 2024-05-13 21:11:36.571745
INFO:root:Script finished at 2024-05-13 21:11:37.311995
[rootiZ7xvavc793m36sybr4bw4Z hub.liheng.work]#