feat: 添加健康报
This commit is contained in:
parent
97ded84a07
commit
eef4121247
179
国内党媒/CrawlJiankangbao.py
Normal file
179
国内党媒/CrawlJiankangbao.py
Normal file
@ -0,0 +1,179 @@
|
||||
# _*_ coding : UTF-8 _*_
|
||||
# @Time : 2024/12/25 17:25
|
||||
# @UpdateTime : 2024/12/25 17:25
|
||||
# @Author : haochen zhong
|
||||
# @File : CrawlJiankangbao.py
|
||||
# @Software : PyCharm
|
||||
# @Comment : 本程序采集健康报版面数据
|
||||
|
||||
|
||||
import asyncio
|
||||
import random
|
||||
from datetime import datetime
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from httpx import AsyncClient
|
||||
from motor.motor_asyncio import AsyncIOMotorClient
|
||||
|
||||
start_date = datetime.strptime('2018-10', '%Y-%m')
|
||||
"""健康报2018年10月份开始有数据"""
|
||||
end_date = datetime.today()
|
||||
"""截止到今天"""
|
||||
headers = {
|
||||
'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.42'}
|
||||
|
||||
# 链接数据库
|
||||
client = AsyncIOMotorClient('mongodb://localhost:27017')
|
||||
db = client['buweijiguanbao']
|
||||
collection = db['jiankangbao']
|
||||
|
||||
|
||||
async def main():
|
||||
collection_names = await db.list_collection_names()
|
||||
# 判断数据表是否存在
|
||||
if "jiankangbao" not in collection_names:
|
||||
# 如果不存在,则从2018年10月开始爬取
|
||||
print("健康报数据表不存在,开始采集!")
|
||||
await getData(start_date, end_date)
|
||||
else:
|
||||
# 如果存在,则从数据库中获取最后一条记录的日期
|
||||
last_record = await collection.find_one({}, sort=[('release_time', -1)])
|
||||
last_date_str = last_record['release_time']
|
||||
print("数据库截止时间:", last_date_str)
|
||||
await getData(last_date_str, end_date)
|
||||
|
||||
|
||||
async def getContent(soup: BeautifulSoup) -> str:
|
||||
"""
|
||||
:param soup: BeautifulSoup对象
|
||||
:return: 文章内容
|
||||
"""
|
||||
content = ""
|
||||
for p in soup.select("#nc_con div"):
|
||||
para = p.text.strip()
|
||||
if para:
|
||||
content += para
|
||||
content += '\n'
|
||||
return content
|
||||
|
||||
|
||||
async def getData(start_date: datetime, end_date: datetime):
|
||||
"""
|
||||
:param start_date: 开始日期
|
||||
:param end_date: 结束日期
|
||||
:return: None
|
||||
"""
|
||||
crawl_num = 0
|
||||
# 创建一个列表保存月份
|
||||
months = []
|
||||
# 从开始日期到结束日期,每个月份都添加到列表中
|
||||
current_date = start_date
|
||||
current_date = current_date.replace(day=1)
|
||||
while current_date <= end_date:
|
||||
months.append(current_date)
|
||||
# 增加一个月
|
||||
if current_date.month == 12:
|
||||
current_date = current_date.replace(year=current_date.year + 1, month=1)
|
||||
else:
|
||||
current_date = current_date.replace(month=current_date.month + 1)
|
||||
# 遍历月份列表
|
||||
for month in months:
|
||||
# 构造URL
|
||||
url = f'https://faxing.jkb.com.cn/home/index/lists.html?goods=1&y={month.strftime("%Y")}&m={month.strftime("%m")}&name=jkb'
|
||||
"""https://faxing.jkb.com.cn/home/index/lists.html?goods=1&y=2018&m=10&name=jkb"""
|
||||
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), url)
|
||||
try:
|
||||
async with AsyncClient(headers=headers, timeout=60) as client:
|
||||
response = await client.get(url)
|
||||
response.encoding = response.charset_encoding
|
||||
print(f"一级连接状态:{response.status_code}")
|
||||
if response.status_code == 200:
|
||||
soup = BeautifulSoup(response.text, 'lxml')
|
||||
for item in soup.select(".list.clearFix a"):
|
||||
url1 = "https://faxing.jkb.com.cn/home/index/menu.html?goods=1&" + "&".join(
|
||||
item.get("href").split("&")[1:-2]) + "&name=jkb"
|
||||
"""https://faxing.jkb.com.cn/home/index/menu.html?goods=1&item=669261&page=137800193&name=jkb"""
|
||||
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), url1)
|
||||
date = datetime.strptime(item.select_one("p").text, "%Y年%m月%d日")
|
||||
response2 = await client.get(url1)
|
||||
response2.encoding = response2.charset_encoding
|
||||
print(f"二级连接状态:{response2.status_code}")
|
||||
if response2.status_code == 200:
|
||||
soup2 = BeautifulSoup(response2.text, 'lxml')
|
||||
for item2 in soup2.select(".banmian2 a"):
|
||||
banmianming = item2.text.strip()
|
||||
banmianhao = ""
|
||||
url2 = "https://faxing.jkb.com.cn" + item2.get("href")
|
||||
"""https://faxing.jkb.com.cn/home/index/content.html?goods=1&item=669261&page=137800193&name=jkb"""
|
||||
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), url2)
|
||||
response3 = await client.get(url2)
|
||||
response3.encoding = response3.charset_encoding
|
||||
print(f"三级连接状态:{response3.status_code}")
|
||||
if response3.status_code == 200:
|
||||
soup3 = BeautifulSoup(response3.text, 'lxml')
|
||||
for item3 in soup3.select(".content a"):
|
||||
url3 = "https://faxing.jkb.com.cn" + item3.get("data-url")
|
||||
"""https://faxing.jkb.com.cn/home/index/detail.html?goods=1&item=669261&page=137800189&id=2240530&name=jkb"""
|
||||
if await collection.find_one({"detail_url": url3}, {"_id": False}):
|
||||
continue
|
||||
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), url3)
|
||||
title = item3.text.strip()
|
||||
response4 = await client.get(url3)
|
||||
response4.encoding = response4.charset_encoding
|
||||
print(f"四级连接状态:{response4.status_code}")
|
||||
if response4.status_code == 200:
|
||||
soup4 = BeautifulSoup(response4.text, 'lxml')
|
||||
try:
|
||||
title = soup4.select_one(".tit").text.strip()
|
||||
except:
|
||||
title = title
|
||||
try:
|
||||
subTitle = soup4.select_one(".vicetitle").text.strip()
|
||||
except:
|
||||
subTitle = ""
|
||||
try:
|
||||
perTitle = soup4.select_one(".introtitle").text.strip()
|
||||
except:
|
||||
perTitle = ""
|
||||
content = await getContent(soup4)
|
||||
await collection.insert_one({
|
||||
"title": title,
|
||||
"subtitle": subTitle,
|
||||
"preTitle": perTitle,
|
||||
"author": "empty",
|
||||
"banmianming": banmianming,
|
||||
"banmianhao": banmianhao,
|
||||
'keywordlist': "empty",
|
||||
'detail_url': url3,
|
||||
'release_time': date,
|
||||
'insert_timestamp': datetime.today(),
|
||||
'content': content
|
||||
})
|
||||
crawl_num += 1
|
||||
print(
|
||||
f"健康报---{date.strftime('%Y-%m-%d')}----{banmianming}---{banmianhao}---{title}---采集完成!")
|
||||
await asyncio.sleep(random.randint(5, 15))
|
||||
print(
|
||||
f"健康报---{date.strftime('%Y-%m-%d')}----{banmianming}---{banmianhao}-----采集完成!")
|
||||
await asyncio.sleep(random.randint(5, 15))
|
||||
print(f"健康报---{date.strftime('%Y-%m-%d')}-----采集完成!")
|
||||
await asyncio.sleep(random.randint(5, 15))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
await collection.insert_one(
|
||||
{'banmianhao': 'empty',
|
||||
'banmianming': 'empty',
|
||||
'preTitle': 'empty',
|
||||
'title': 'empty',
|
||||
'subtitle': 'empty',
|
||||
'author': 'empty',
|
||||
'keywordlist': 'empty',
|
||||
'detail_url': url,
|
||||
'release_time': datetime.today(),
|
||||
'insert_timestamp': datetime.today(),
|
||||
'content': 'empty'}
|
||||
)
|
||||
print(f"健康报采集完毕,共采集{crawl_num}条数据!")
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@ -14,4 +14,5 @@
|
||||
| 12 | ✅ | 中华人民共和国生态环境部 | [中国环境报](./CrawlZhongguohuanjingbao.py) | [news.cenews.com.cn](http://news.cenews.com.cn/html/2024-10/30/node_2.htm) | buweijiguanbao | zhongguohuanjingbao | 中国环境报2013年8月开始有数据 |
|
||||
| 13 | ✅ | 中华人民共和国农业农村部 | [农民日报](./CrawlNongminribao.py) | [szb.farmer.com.cn](https://szb.farmer.com.cn/nmrb/html/2024/20241127/20241127_1/nmrb_20241127_12872_1.html) | buweijiguanbao | nongminribao | 农民日报2021年1月13日开始有数据 |
|
||||
| 14 | ✅ | 中华人民共和国商务部 | [国际商报](./CrawlGuojishangbao.py) | [epa.comnews.cn](https://epa.comnews.cn/pc/layout/202208/26/node_01.html) | buweijiguanbao | guojishangbao | 国际商报2022年8月1日开始有数据 |
|
||||
| 15 | ✅ | 中华人民共和国文化和旅游部 | [中国文化报](./CrawlZhongguolvyoubao.py) | [npaper.ccmapp.cn](https://npaper.ccmapp.cn/zh-CN/?page=1) | buweijiguanbao | zhongguolvyoubao | 中国文化报2008年8月开始有数据 |
|
||||
| 15 | ✅ | 中华人民共和国文化和旅游部 | [中国文化报](./CrawlZhongguowenhuabao.py) | [npaper.ccmapp.cn](https://npaper.ccmapp.cn/zh-CN/?page=1) | buweijiguanbao | zhongguolvyoubao | 中国文化报2008年8月开始有数据 |
|
||||
| 16 | ✅ | 中华人民共和国国家卫生健康委员会 | [健康报](./CrawlJiankangbao.py) | [faxing.jkb.com.cn](https://faxing.jkb.com.cn/) | buweijiguanbao | jiankangbao | 健康报2018年10月开始有数据 |
|
||||
Loading…
x
Reference in New Issue
Block a user