完成github监控部分的程序
This commit is contained in:
1 parent
247eaa5145
commit
1356dcc25c
32 files changed
+923
-501
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,197 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import requests
|
||||
import xml.etree.ElementTree as ET
|
||||
import json
|
||||
from requests.exceptions import RequestException
|
||||
from loguru import logger
|
||||
|
||||
# 测试用爬虫请求头
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-cache",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9"
|
||||
}
|
||||
|
||||
doonsec_headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "none",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Priority": "u=0, i",
|
||||
"Te": "trailers",
|
||||
"Connection": "keep-alive"
|
||||
}
|
||||
|
||||
def fetch_rss(url, headers, timeout=60):
|
||||
try:
|
||||
response = requests.get(url, headers=headers, timeout=timeout)
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
return response.content
|
||||
except requests.Timeout:
|
||||
logger.warning(f"请求 {url} 超时,跳过保存操作。")
|
||||
return None
|
||||
except RequestException as e:
|
||||
logger.error(f"请求 {url} 时发生错误: {e}")
|
||||
return None # 返回None表示请求失败
|
||||
|
||||
def parse_rss(rss_content):
|
||||
items = []
|
||||
root = ET.fromstring(rss_content)
|
||||
for item in root.findall('.//item'):
|
||||
item_dict = {}
|
||||
for child in item:
|
||||
item_dict[child.tag] = child.text
|
||||
items.append(item_dict)
|
||||
return items
|
||||
|
||||
def save_to_json(data, filename):
|
||||
with open(filename, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
# seebug 爬虫
|
||||
def seebug_main():
|
||||
url = "https://paper.seebug.org/rss/"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取Seebug社区RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/seebug.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/seebug.json')
|
||||
logger.info("数据已保存到 ./JSON/seebug.json!")
|
||||
|
||||
# 4hou 爬虫
|
||||
def M_4hou_main():
|
||||
url = "https://www.4hou.com/feed"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取嘶吼RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/4hou.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/4hou.json')
|
||||
logger.info("数据已保存到 ./JSON/4hou.json!")
|
||||
|
||||
# 安全客 爬虫
|
||||
def anquanke_main():
|
||||
url = "https://api.anquanke.com/data/v1/rss"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取安全客RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/anquanke.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/anquanke.json')
|
||||
logger.info("数据已保存到 ./JSON/anquanke.json!")
|
||||
|
||||
# sec_wiki 爬虫
|
||||
def sec_wiki_main():
|
||||
url = "https://www.sec_wiki.com/news/rss"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取安全维基RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/sec_wiki.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/sec_wiki.json')
|
||||
logger.info("数据已保存到 ./JSON/sec_wiki.json!")
|
||||
|
||||
# 华为 爬虫
|
||||
def huawei_main():
|
||||
url = "https://www.huawei.com/cn/rss-feeds/psirt/rss"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取华为RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/huawei.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/huawei.json')
|
||||
logger.info("数据已保存到 ./JSON/huawei.json!")
|
||||
|
||||
# 洞见微信聚合爬虫
|
||||
def doonsec_main():
|
||||
url = "https://wechat.doonsec.com/bayes_rss.xml"
|
||||
rss_content = fetch_rss(url, doonsec_headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取洞见微信聚合RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/doonsec.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/doonsec.json')
|
||||
logger.info("数据已保存到 ./JSON/doonsec.json!")
|
||||
|
||||
# 奇安信攻防社区 爬虫
|
||||
def qianxin_main():
|
||||
url = "https://forum.butian.net/Rss"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取奇安信攻防社区RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/qianxin.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/qianxin.json')
|
||||
logger.info("数据已保存到 ./JSON/qianxin.json!")
|
||||
|
||||
def run():
|
||||
seebug_main()
|
||||
M_4hou_main()
|
||||
anquanke_main()
|
||||
# sec_wiki_main()
|
||||
huawei_main()
|
||||
doonsec_main()
|
||||
qianxin_main()
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import requests
|
||||
import xml.etree.ElementTree as ET
|
||||
import json
|
||||
from requests.exceptions import RequestException
|
||||
from loguru import logger
|
||||
|
||||
# 测试用爬虫请求头
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-cache",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9"
|
||||
}
|
||||
|
||||
def fetch_rss(url, headers, timeout=20):
|
||||
try:
|
||||
response = requests.get(url, headers=headers, timeout=timeout)
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
return response.content
|
||||
except requests.Timeout:
|
||||
logger.warning(f"请求 {url} 超时,跳过保存操作。")
|
||||
return None
|
||||
except RequestException as e:
|
||||
logger.error(f"请求 {url} 时发生错误: {e}")
|
||||
return None # 返回None表示请求失败
|
||||
|
||||
def parse_rss(rss_content):
|
||||
items = []
|
||||
root = ET.fromstring(rss_content)
|
||||
for item in root.findall('.//item'):
|
||||
item_dict = {}
|
||||
for child in item:
|
||||
tag = child.tag
|
||||
# 将一标签替换名称方便处理
|
||||
if tag.startswith('{http://purl.org/rss/1.0/modules/content/}'):
|
||||
tag = 'body'
|
||||
item_dict[tag] = child.text
|
||||
items.append(item_dict)
|
||||
return items
|
||||
|
||||
def save_to_json(data, filename):
|
||||
with open(filename, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def freebuf_main():
|
||||
url = "https://www.freebuf.com/feed"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取Freebuf RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
try:
|
||||
items = parse_rss(rss_content)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/freebuf.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
save_to_json(items, './JSON/freebuf.json')
|
||||
logger.info("数据已保存到 ./JSON/freebuf.json!")
|
||||
except Exception as e:
|
||||
logger.error(f"解析或保存Freebuf RSS内容时发生错误: {e}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
freebuf_main()
|
||||
@@ -0,0 +1,189 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time
|
||||
import yaml
|
||||
import requests
|
||||
import json
|
||||
import datetime
|
||||
from requests.exceptions import RequestException
|
||||
import xml.etree.ElementTree as ET
|
||||
from loguru import logger
|
||||
|
||||
MAX_DESCRIPTION_LENGTH = 300
|
||||
|
||||
with open('./config/github_config.yaml', 'r', encoding="utf-8") as file:
|
||||
config = yaml.safe_load(file)
|
||||
# list = yaml.load(f,Loader=yaml.FullLoader)
|
||||
token = config['github_token']
|
||||
tool_list, keyword_list, user_list, black_words = config['tool_list'], config['keyword_list'], config['user_list'], config['black_words']
|
||||
|
||||
def fetch_rss(url, timeout=10):
|
||||
if token is None:
|
||||
headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
else:
|
||||
headers = {
|
||||
'Authorization': f"token {token}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.get(url, headers=headers, timeout=timeout)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.Timeout:
|
||||
logger.warning(f"请求 {url} 超时,跳过保存操作。")
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"请求 {url} 时发生错误: {e}")
|
||||
|
||||
def save_to_json(data, filename):
|
||||
with open(filename, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def github_main_keyword(key):
|
||||
all_results = [] # 用于存储所有结果
|
||||
for keyword in key:
|
||||
logger.info(f"github_keyword:关键词【{keyword}】获取开始。")
|
||||
api_node = "https://api.github.com/search/repositories?q={}&sort=updated&per_page=20".format(keyword)
|
||||
result = fetch_rss(api_node)
|
||||
for i in range(0, 20):
|
||||
description = result['items'][i]['description']
|
||||
|
||||
if description is None:
|
||||
pass
|
||||
# 检查描述中是否包含黑名单词汇
|
||||
elif any(word in description for word in black_words):
|
||||
continue # 跳过本次执行
|
||||
# 截断描述并在300字节处添加...
|
||||
elif len(description.encode('utf-8')) > MAX_DESCRIPTION_LENGTH:
|
||||
# 找到300字节处的索引
|
||||
byte_index = 0
|
||||
char_index = 0
|
||||
while byte_index < MAX_DESCRIPTION_LENGTH and char_index < len(description):
|
||||
byte_index += len(description[char_index].encode('utf-8'))
|
||||
char_index += 1
|
||||
description = description[:char_index - 1] + '...'
|
||||
|
||||
link = result['items'][i]['html_url']
|
||||
name = result['items'][i]['name']
|
||||
created_at = result['items'][i]['created_at']
|
||||
author = result['items'][i]['owner']['login']
|
||||
language = result['items'][i]['language']
|
||||
|
||||
# 将每个项目的详细信息存储在一个字典中
|
||||
project_info = {
|
||||
'link': link,
|
||||
'name': name,
|
||||
'created_at': created_at,
|
||||
'description': description,
|
||||
'author': author,
|
||||
'language': language,
|
||||
'keyword': keyword
|
||||
}
|
||||
# print(project_info)
|
||||
all_results.append(project_info)
|
||||
time.sleep(10)
|
||||
|
||||
# 将所有结果写入JSON文件
|
||||
save_to_json(all_results, './JSON/github_keyword.json')
|
||||
|
||||
|
||||
def github_main_repo(key):
|
||||
all_results = [] # 用于存储所有结果
|
||||
for keyword in key:
|
||||
logger.info(f"github_repo:项目【{keyword}】更新情况获取开始。")
|
||||
api_node = "https://api.github.com/repos/{}/commits?per_page=1".format(keyword)
|
||||
result = fetch_rss(api_node)
|
||||
|
||||
commit = result[0] # 获取最新的提交记录
|
||||
description = commit['commit']['message']
|
||||
|
||||
if description is None:
|
||||
pass
|
||||
# 截断描述并在300字节处添加...
|
||||
elif len(description.encode('utf-8')) > MAX_DESCRIPTION_LENGTH:
|
||||
byte_index = 0
|
||||
char_index = 0
|
||||
while byte_index < MAX_DESCRIPTION_LENGTH and char_index < len(description):
|
||||
byte_index += len(description[char_index].encode('utf-8'))
|
||||
char_index += 1
|
||||
description = description[:char_index - 1] + '...'
|
||||
|
||||
author = commit['commit']['author']['name']
|
||||
updated_at = commit['commit']['author']['date']
|
||||
link_2 = commit['html_url']
|
||||
|
||||
# 将每个项目的详细信息存储在一个字典中
|
||||
project_info = {
|
||||
'link': f"https://api.github.com/{keyword}",
|
||||
'name': keyword,
|
||||
'updated_at': updated_at,
|
||||
'description': description,
|
||||
'author': author,
|
||||
'link_2': link_2,
|
||||
'keyword': keyword
|
||||
}
|
||||
# print(project_info)
|
||||
all_results.append(project_info)
|
||||
time.sleep(10)
|
||||
|
||||
# 将所有结果写入JSON文件
|
||||
save_to_json(all_results, './JSON/github_repo.json')
|
||||
|
||||
def github_main_user(key):
|
||||
all_results = [] # 用于存储所有结果
|
||||
for keyword in key:
|
||||
logger.info(f"github_user:作者【{keyword}】更新情况获取开始。")
|
||||
api_node = "https://api.github.com/users/{}/repos?sort=created&per_page=10".format(keyword)
|
||||
result = fetch_rss(api_node)
|
||||
for i in range(0, len(result)):
|
||||
description = result[i]['description']
|
||||
|
||||
if description is None:
|
||||
pass
|
||||
# 检查描述中是否包含黑名单词汇
|
||||
elif any(word in description for word in black_words):
|
||||
continue # 跳过本次执行
|
||||
# 截断描述并在300字节处添加...
|
||||
elif len(description.encode('utf-8')) > MAX_DESCRIPTION_LENGTH:
|
||||
# 找到300字节处的索引
|
||||
byte_index = 0
|
||||
char_index = 0
|
||||
while byte_index < MAX_DESCRIPTION_LENGTH and char_index < len(description):
|
||||
byte_index += len(description[char_index].encode('utf-8'))
|
||||
char_index += 1
|
||||
description = description[:char_index - 1] + '...'
|
||||
|
||||
link = result[i]['html_url']
|
||||
name = result[i]['name']
|
||||
created_at = result[i]['created_at']
|
||||
author = result[i]['owner']['login']
|
||||
language = result[i]['language']
|
||||
|
||||
# 将每个项目的详细信息存储在一个字典中
|
||||
project_info = {
|
||||
'link': link,
|
||||
'name': name,
|
||||
'created_at': created_at,
|
||||
'description': description,
|
||||
'author': author,
|
||||
'language': language,
|
||||
'keyword': keyword
|
||||
}
|
||||
# print(project_info)
|
||||
all_results.append(project_info)
|
||||
time.sleep(10)
|
||||
|
||||
# 将所有结果写入JSON文件
|
||||
save_to_json(all_results, './JSON/github_user.json')
|
||||
|
||||
def github_main():
|
||||
if keyword_list:
|
||||
github_main_keyword(keyword_list)
|
||||
if tool_list:
|
||||
github_main_repo(tool_list)
|
||||
if user_list:
|
||||
github_main_user(user_list)
|
||||
|
||||
if __name__ == "__main__":
|
||||
github_main()
|
||||
@@ -0,0 +1,119 @@
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
import json
|
||||
import time
|
||||
import os
|
||||
import datetime
|
||||
from requests.exceptions import RequestException
|
||||
from loguru import logger
|
||||
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "none",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Priority": "u=0, i",
|
||||
"Te": "trailers",
|
||||
"Connection": "keep-alive"
|
||||
}
|
||||
|
||||
def fetch_html(url, headers=headers, timeout=10):
|
||||
try:
|
||||
response = requests.get(url, headers=headers, timeout=timeout)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
except requests.Timeout:
|
||||
logger.warning(f"请求 {url} 超时,跳过保存操作。")
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"请求 {url} 时发生错误: {e}")
|
||||
|
||||
def parse_html(html_content):
|
||||
soup = BeautifulSoup(html_content, 'html.parser')
|
||||
|
||||
# 提取所有符合条件的<li>标签
|
||||
items = soup.find_all('li', id=lambda x: x and x.startswith('sogou_vr_11002601_box_'))
|
||||
|
||||
results = []
|
||||
|
||||
for item in items:
|
||||
# 提取标题和链接
|
||||
title_tag = item.find('h3')
|
||||
if title_tag:
|
||||
a_tag = title_tag.find('a')
|
||||
title = title_tag.get_text(strip=True) if title_tag else "No title found"
|
||||
link = a_tag['href'] if a_tag else "No link found"
|
||||
if link and not link.startswith('http'):
|
||||
link = "https://weixin.sogou.com" + link
|
||||
else:
|
||||
title = "No title found"
|
||||
link = "No link found"
|
||||
|
||||
# 提取摘要
|
||||
summary_tag = item.find('p', class_='txt-info')
|
||||
summary = summary_tag.get_text(strip=True) if summary_tag else "No summary found"
|
||||
|
||||
# 提取发布者
|
||||
publisher_tag = item.find('span', class_='all-time-y2')
|
||||
publisher = publisher_tag.get_text(strip=True) if publisher_tag else "No publisher found"
|
||||
|
||||
# 提取时间戳并转换为标准时间格式
|
||||
timestamp_script = item.find('script', string=lambda text: 'document.write(timeConvert' in text)
|
||||
if timestamp_script:
|
||||
timestamp_str = timestamp_script.string.split("'")[1]
|
||||
timestamp = int(timestamp_str)
|
||||
standard_time = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
|
||||
else:
|
||||
standard_time = "No timestamp found"
|
||||
|
||||
results.append({
|
||||
"title": title,
|
||||
"link": link,
|
||||
"description": summary,
|
||||
"author": publisher,
|
||||
"pubDate": standard_time
|
||||
})
|
||||
|
||||
return results
|
||||
|
||||
def remove_surrogates(text):
|
||||
"""移除非法代理对"""
|
||||
return text.encode('utf-8', 'ignore').decode('utf-8')
|
||||
|
||||
def sougou_wx_main(keywords):
|
||||
all_results = {} # 用于存储所有关键词的结果
|
||||
|
||||
for keyword in keywords:
|
||||
url = f"https://weixin.sogou.com/weixin?type=2&s_from=input&ie=utf8&query={keyword}"
|
||||
html_content = fetch_html(url)
|
||||
# print(html_content)
|
||||
|
||||
if html_content is None:
|
||||
logger.warning(f"无法获取微信公众号-Sogou搜索内容,跳过保存操作。关键词: {keyword}")
|
||||
continue
|
||||
|
||||
results = parse_html(html_content)
|
||||
# 移除非法代理对
|
||||
cleaned_results = [{k: remove_surrogates(v) for k, v in item.items()} for item in results]
|
||||
logger.warning(f"关键词【{keyword}】的微信公众号-Sogou搜索内容保存成功。")
|
||||
all_results[keyword] = cleaned_results # 将结果存储在字典中,以关键词为键
|
||||
time.sleep(5)
|
||||
|
||||
# 将所有结果转换为JSON格式
|
||||
json_results = json.dumps(all_results, ensure_ascii=False, indent=4)
|
||||
# print(json_results)
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(os.path.dirname('./JSON/sougou-wx.json'), exist_ok=True)
|
||||
|
||||
# 将解析后的数据保存到 JSON 文件
|
||||
with open('./JSON/sougou-wx.json', 'w', encoding='utf-8') as f:
|
||||
f.write(json_results)
|
||||
|
||||
if __name__ == "__main__":
|
||||
keywords = ["齐鲁银行", "APP逆向", "渗透测试"]
|
||||
sougou_wx_main(keywords)
|
||||
@@ -0,0 +1,73 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import requests
|
||||
import xmltodict
|
||||
import json
|
||||
from loguru import logger
|
||||
|
||||
# 测试用爬虫请求头
|
||||
headers = {
|
||||
"Content-Type": "application/atom+xml; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36",
|
||||
"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"
|
||||
}
|
||||
|
||||
def fetch_rss(url, headers, timeout=20):
|
||||
try:
|
||||
response = requests.get(url, headers=headers, timeout=timeout)
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
return response.content
|
||||
except requests.Timeout:
|
||||
logger.warning(f"请求 {url} 超时,跳过保存操作。")
|
||||
return None
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"请求 {url} 时发生错误: {e}")
|
||||
return None # 返回None表示请求失败
|
||||
|
||||
# 先知社区 爬虫
|
||||
def xianzhi_main():
|
||||
url = "https://xz.aliyun.com/feed"
|
||||
rss_content = fetch_rss(url, headers)
|
||||
|
||||
if rss_content is None:
|
||||
logger.warning("无法获取先知社区RSS内容,跳过保存操作。")
|
||||
return
|
||||
|
||||
try:
|
||||
# 将 XML 数据转换为 Python 字典
|
||||
data = xmltodict.parse(rss_content)
|
||||
|
||||
# 提取所有的 <entry> 元素
|
||||
entries = data['feed'].get('entry', [])
|
||||
|
||||
# 创建一个空列表来存储每个 <entry> 的 JSON 数据
|
||||
entries_json = []
|
||||
|
||||
# 遍历每个 <entry> 元素,提取信息,并添加到列表中
|
||||
for entry in entries:
|
||||
entry_dict = {
|
||||
'title': entry.get('title', ''),
|
||||
'link': entry.get('link', {}).get('@href', ''), # 提取链接
|
||||
'published': entry.get('published', ''),
|
||||
'id': entry.get('id', ''),
|
||||
'summary': entry.get('summary', '')
|
||||
}
|
||||
entries_json.append(entry_dict)
|
||||
|
||||
# 将 <entry> 元素的列表转换为 JSON 格式
|
||||
json_data = json.dumps(entries_json, ensure_ascii=False, indent=4)
|
||||
|
||||
# 保存 JSON 数据到文件
|
||||
with open('./JSON/xianzhi.json', 'w', encoding='utf-8') as json_file:
|
||||
json_file.write(json_data)
|
||||
|
||||
logger.info("数据已保存到 ./JSON/xianzhi.json!")
|
||||
except Exception as e:
|
||||
logger.error(f"解析或保存先知社区RSS内容时发生错误: {e}")
|
||||
|
||||
# 示例调用
|
||||
if __name__ == "__main__":
|
||||
xianzhi_main()
|
||||
Reference in new issue
Block a user