feat: 增加农民日报
This commit is contained in:
parent
d7af12b06e
commit
33527d0492
152
国内党媒/CrawlNongminribao.py
Normal file
152
国内党媒/CrawlNongminribao.py
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
# _*_ coding : UTF-8 _*_
|
||||||
|
# @Time : 2024/11/27 21:13
|
||||||
|
# @UpdateTime : 2024/11/27 21:13
|
||||||
|
# @Author : haochen zhong
|
||||||
|
# @File : CrawlNongminribao.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('2021-01', '%Y-%m')
|
||||||
|
"""农民日报2021年1月份开始有数据"""
|
||||||
|
end_date = datetime.today()
|
||||||
|
"""截止到今天"""
|
||||||
|
headers = {
|
||||||
|
"connection": 'keep-alive',
|
||||||
|
"host": "szb.farmer.com.cn",
|
||||||
|
'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['nongminribao']
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
collection_names = await db.list_collection_names()
|
||||||
|
# 判断数据表是否存在
|
||||||
|
if "nongminribao" not in collection_names:
|
||||||
|
# 如果不存在,则从2017年9月开始爬取
|
||||||
|
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("#ozoom p"):
|
||||||
|
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
|
||||||
|
start_date = int(start_date.strftime("%Y%m%d"))
|
||||||
|
try:
|
||||||
|
async with AsyncClient(headers=headers, timeout=60) as client:
|
||||||
|
response = await client.get("https://szb.farmer.com.cn/nmrb/period/yearMonthDay.json")
|
||||||
|
response.encoding = response.charset_encoding
|
||||||
|
print(f"一级连接状态:{response.status_code}")
|
||||||
|
if response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
dayList = []
|
||||||
|
for value in data.values():
|
||||||
|
for item in value.values():
|
||||||
|
dayList += item
|
||||||
|
dayList.sort()
|
||||||
|
dayList = list(filter(lambda x: x >= start_date, list(map(int, dayList))))
|
||||||
|
for day in dayList:
|
||||||
|
try:
|
||||||
|
url = f"https://szb.farmer.com.cn/nmrb/html/{day.__str__()[:4]}/{day}/data.json"
|
||||||
|
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), url)
|
||||||
|
response = await client.get(url)
|
||||||
|
response.encoding = response.charset_encoding
|
||||||
|
print(f"二级连接状态:{response.status_code}")
|
||||||
|
if response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
for item in data:
|
||||||
|
banmianming = item["pageName"]
|
||||||
|
banmianhao = f"第{item['pageNo']}版"
|
||||||
|
for article in item["onePageArticleList"]:
|
||||||
|
title = article["mainTitle"]
|
||||||
|
url2 = f"https://szb.farmer.com.cn/nmrb/html/{day.__str__()[:4]}/{day}/{day}_{item['pageNo']}/{article['articleHref']}"
|
||||||
|
"""https://szb.farmer.com.cn/nmrb/html/2024/20241127/20241127_1/nmrb_20241127_12872_1_1861525833392427013.html"""
|
||||||
|
if await collection.find_one({"detail_url": url2}, {"_id": False}):
|
||||||
|
continue
|
||||||
|
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), url2)
|
||||||
|
response2 = await client.get(url2)
|
||||||
|
response2.encoding = response2.charset_encoding
|
||||||
|
print(f"三级连接状态:{response2.status_code}")
|
||||||
|
if response2.status_code == 200:
|
||||||
|
soup = BeautifulSoup(response2.text, "lxml")
|
||||||
|
preTitle = soup.select_one("#PreTitle").text
|
||||||
|
title = soup.select_one("#Title").text
|
||||||
|
subTitle = soup.select_one("#SubTitle").text
|
||||||
|
author = soup.select_one(".author-style").text
|
||||||
|
content = await getContent(soup)
|
||||||
|
await collection.insert_one({
|
||||||
|
"title": title,
|
||||||
|
"subtitle": subTitle,
|
||||||
|
"preTitle": preTitle,
|
||||||
|
"author": author,
|
||||||
|
"banmianming": banmianming,
|
||||||
|
"banmianhao": banmianhao,
|
||||||
|
'keywordlist': "empty",
|
||||||
|
'detail_url': url2,
|
||||||
|
'release_time': datetime.strptime(str(day), "%Y%m%d"),
|
||||||
|
'insert_timestamp': datetime.today(),
|
||||||
|
'content': content
|
||||||
|
})
|
||||||
|
crawl_num += 1
|
||||||
|
print(
|
||||||
|
f"农民日报---{day}---{banmianming}---{banmianhao}---{title}---采集完成!")
|
||||||
|
await asyncio.sleep(random.randint(5, 15))
|
||||||
|
print(f"农民日报---{day}---{banmianming}---{banmianhao}-----采集完成!")
|
||||||
|
await asyncio.sleep(random.randint(5, 15))
|
||||||
|
print(f"农民日报---{day}-----采集完成!")
|
||||||
|
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.strptime(str(day), "%Y%m%d"),
|
||||||
|
'insert_timestamp': datetime.today(),
|
||||||
|
'content': 'empty'}
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
print(f"农民日报采集完毕,共采集{crawl_num}条数据!")
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
@ -11,4 +11,5 @@
|
|||||||
| 9 | ✅ | 中华人民共和国司法部 | [法治日报](./CrawlFazhiribao.py) | [epaper.legaldaily.com.cn](http://epaper.legaldaily.com.cn/fzrb/content/20210101/Page01TB.htm) | buweijiguanbao | fazhiribao | 法治日报2021年1月1日开始有数据 |
|
| 9 | ✅ | 中华人民共和国司法部 | [法治日报](./CrawlFazhiribao.py) | [epaper.legaldaily.com.cn](http://epaper.legaldaily.com.cn/fzrb/content/20210101/Page01TB.htm) | buweijiguanbao | fazhiribao | 法治日报2021年1月1日开始有数据 |
|
||||||
| 10 | ✅ | 中华人民共和国财政部 | [中国财经报](./CrawlZhongguocaijingbao.py) | [114.118.9.73](http://114.118.9.73/epaper/) | buweijiguanbao | zhongguocaijingbao | 中国财经报2017年11月份开始有数据 |
|
| 10 | ✅ | 中华人民共和国财政部 | [中国财经报](./CrawlZhongguocaijingbao.py) | [114.118.9.73](http://114.118.9.73/epaper/) | buweijiguanbao | zhongguocaijingbao | 中国财经报2017年11月份开始有数据 |
|
||||||
| 11 | ✅ | 中华人民共和国自然资源部 | [中国自然资源报](./CrawlZhongguoziranziyuanbao.py) | [szb.iziran.net](http://szb.iziran.net/bz/html/index.html?date=2024-11-21&cid=1) | buweijiguanbao | zhongguoziranziyuanbao | 中国自然资源报2018年5月18日开始有数据 |
|
| 11 | ✅ | 中华人民共和国自然资源部 | [中国自然资源报](./CrawlZhongguoziranziyuanbao.py) | [szb.iziran.net](http://szb.iziran.net/bz/html/index.html?date=2024-11-21&cid=1) | buweijiguanbao | zhongguoziranziyuanbao | 中国自然资源报2018年5月18日开始有数据 |
|
||||||
| 12 | ✅ | 中华人民共和国生态环境部 | [中国环境报](./CrawlZhongguohuanjingbao.py) | [news.cenews.com.cn](http://news.cenews.com.cn/html/2024-10/30/node_2.htm) | buweijiguanbao | zhongguohuanjingbao | 中国环境报2013年8月开始有数据 |
|
| 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日开始有数据 |
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user