返回作品
AI

自动化抓取脚本(可用于AI知识库,SEO)

  • 抓包
  • 批量抓取文章
  • 自动化
  • seo
  • 知识库

产品详情

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
cinn_spider.py —— 抓取xx新闻网指定月份的全部文章

流程:
1. 抓首页,收集所有栏目(*/index.html)
2. 逐个栏目翻页(index.html -> index_2.html ...),直到该页不再出现目标月份文章
3. 汇总去重所有 /YYYY/MM-DD/xxx.html 文章链接
4. 逐篇抓取标题、来源、发布时间、正文,保存为 txt + 汇总 json/md

用法:
python3 cinn_spider.py # 默认 2026-11
python3 cinn_spider.py --month 2026-10
"""

import argparse
import http.cookiejar
import json
import os
import re
import sys
import time
import urllib.request
from html.parser import HTMLParser

try:
sys.stdout.reconfigure(line_buffering=True)
except Exception:
pass

HOME = "https://" // 目标地址
HOST = "https://" // 目标地址
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

ART_RE = re.compile(r"^/[A-Za-z0-9_\-/]*?/(\d{4})/(\d{2})-(\d{2})/([A-Za-z0-9]+)\.html$")

# --------------------------------------------------------------------------
# 网络
# --------------------------------------------------------------------------
class Fetcher(object):
def __init__(self, delay=0.6):
self.jar = http.cookiejar.CookieJar()
self.opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(self.jar))
self.delay = delay
self.requests = 0

def get(self, url, retries=3):
for attempt in range(retries):
try:
req = urllib.request.Request(url, headers={
"User-Agent": UA,
"Referer": HOME,
"Accept": "text/html,application/xhtml+xml,*/*",
"Accept-Language": "zh-CN,zh;q=0.9",
})
with self.opener.open(req, timeout=30) as resp:
raw = resp.read()
charset = resp.headers.get_content_charset() or "utf-8"
self.requests += 1
time.sleep(self.delay)
return raw.decode(charset, "replace")
except Exception:
time.sleep(1.5 * (attempt + 1))
print(" [失败] %s" % url)
return ""

# --------------------------------------------------------------------------
# 链接收集
# --------------------------------------------------------------------------
def collect_sections(html):
"""从首页提取所有栏目路径,如 /bw/、/difang/henan/。"""
sections = {"/"}
for href in re.findall(r'href="([^"]+)"', html):
h = href.strip()
for prefix in ("//www.cinn.cn", "https://www.cinn.cn", "http://www.cinn.cn"):
if h.startswith(prefix):
h = h[len(prefix):]
break
if not h.startswith("/"):
continue
if re.match(r"^/[A-Za-z0-9_\-/]*index\.html$", h) and "/h5/" not in h:
path = h[:-len("index.html")]
if path.count("/") <= 3:
sections.add(path)
return sorted(sections)

def page_url(section, page_no):
base = section.rstrip("/")
if page_no == 1:
return HOST + base + "/index.html"
return "%s%s/index_%d.html" % (HOST, base, page_no)

def extract_articles(html, month):
"""提取本页中属于指定年月的文章链接(返回相对路径列表)。"""
found = []
for href in re.findall(r'href="([^"]+)"', html):
h = href.strip()
for prefix in ("//www.cinn.cn", "https://www.cinn.cn", "http://www.cinn.cn"):
if h.startswith(prefix):
h = h[len(prefix):]
break
m = ART_RE.match(h)
if not m:
continue
if "%s-%s" % (m.group(1), m.group(2)) == month:
found.append(h)
return found

# --------------------------------------------------------------------------
# 正文解析
# --------------------------------------------------------------------------
class ArticleExtractor(HTMLParser):
def __init__(self):
HTMLParser.__init__(self, convert_charrefs=True)
self.title = ""
self.source = ""
self.publish = ""
self.content_parts = []

self._in_title = False
self._in_source = False
self._in_publish = False
self._in_content = False
self._content_depth = 0
self._skip = 0

def handle_starttag(self, tag, attrs):
cls = (dict(attrs).get("class") or "").split()

if tag in ("script", "style"):
self._skip += 1
return

if tag == "div" and "title" in cls and not self.title:
self._in_title = True
if tag == "span" and "source" in cls:
self._in_source = True
if tag == "span" and "publish_at_str" in cls:
self._in_publish = True

if tag == "div" and "imagetext-content" in cls and not self._in_content:
self._in_content = True
self._content_depth = 1
return

if self._in_content:
if tag == "div":
self._content_depth += 1
elif tag in ("p", "br", "li", "h1", "h2", "h3", "h4"):
self.content_parts.append("\n")

def handle_startendtag(self, tag, attrs):
if self._in_content and tag == "br":
self.content_parts.append("\n")

def handle_endtag(self, tag):
if tag in ("script", "style"):
if self._skip:
self._skip -= 1
return

if tag == "div" and self._in_title:
self._in_title = False
return
if tag == "span" and self._in_source:
self._in_source = False
return
if tag == "span" and self._in_publish:
self._in_publish = False
return

if self._in_content:
if tag == "div":
self._content_depth -= 1
if self._content_depth <= 0:
self._in_content = False
elif tag in ("p", "li", "h1", "h2", "h3", "h4"):
self.content_parts.append("\n")

def handle_data(self, data):
if self._skip:
return
if self._in_title and not self.title.strip():
self.title += data
elif self._in_source:
self.source += data
elif self._in_publish:
self.publish += data
if self._in_content:
self.content_parts.append(data)

def content(self):
text = "".join(self.content_parts)
text = re.sub(r"[ \t\u00a0]+", " ", text)
text = re.sub(r"\n\s*\n+", "\n\n", text)
return text.strip()

def parse_article(html):
parser = ArticleExtractor()
try:
parser.feed(html)
parser.close()
except Exception:
pass

title = re.sub(r"\s+", " ", parser.title).strip()
source = re.sub(r"来源\s*[::]?", "", parser.source)
source = re.sub(r"\s+", " ", source).strip()
publish = parser.publish.strip()
return title, source, publish, parser.content()

# --------------------------------------------------------------------------
def safe_name(text):
text = re.sub(r"[^\w.\-]+", "_", text)
return text.strip("_")[:120] or "article"

def main():
ap = argparse.ArgumentParser(description="抓取 cinn.cn 指定月份全部文章")
ap.add_argument("--month", default="2026-11", help="年月,如 2026-11")
ap.add_argument("-o", "--out", default=os.path.join(os.path.dirname(__file__), "cinn_2026_11"))
ap.add_argument("--max-pages", type=int, default=8)
args = ap.parse_args()

month = args.month
outdir = args.out
pages_dir = os.path.join(outdir, "articles")
os.makedirs(pages_dir, exist_ok=True)

fetcher = Fetcher()

print("[1/4] 抓首页并收集栏目 ...")
home = fetcher.get(HOME)
if not home:
print("首页抓取失败,退出。")
return
sections = collect_sections(home)
print(" 发现 %d 个栏目: %s" % (len(sections), " ".join(sections)))

print("[2/4] 逐栏目翻页收集 %s 文章链接 ..." % month)
article_set = set()
for section in sections:
section_count = 0
seen_pages = set()
for page_no in range(1, args.max_pages + 1):
html = fetcher.get(page_url(section, page_no))
if not html:
break
found = extract_articles(html, month)
if not found:
break
signature = frozenset(found)
if signature in seen_pages:
# 分页不存在时站点会回落到同一列表页,避免重复翻页
break
seen_pages.add(signature)
before = len(article_set)
article_set.update(found)
section_count += len(found)
new_count = len(article_set) - before
print(" %-24s 第%d页 +%d 篇(新 %d)" % (section, page_no, len(found), new_count))
if len(found) < 3:
break
if section_count == 0:
print(" %-24s 无 %s 文章" % (section, month))

articles = sorted(article_set)
print(" 合计去重后 %d 篇" % len(articles))

print("[3/4] 抓取文章正文 ...")
records = []
for idx, path in enumerate(articles, 1):
url = HOST + path
html = fetcher.get(url)
if not html:
continue
title, source, publish, content = parse_article(html)
if not title or not content:
print(" [跳过] %s(解析失败)" % path)
continue

date_part = re.search(r"/(\d{4})/(\d{2})-(\d{2})/", path)
day = "%s-%s-%s" % date_part.groups() if date_part else ""
filename = safe_name("%s_%s" % (day, title)) + ".txt"

record = {
"title": title,
"publish": publish,
"source": source,
"url": url,
"date": day,
"file": filename,
"words": len(content),
}
records.append(record)

body = (
"标题: %s\n"
"发布时间: %s\n"
"来源: %s\n"
"URL: %s\n"
"%s\n\n%s\n"
% (title, publish, source, url, "=" * 60, content)
)
with open(os.path.join(pages_dir, filename), "w", encoding="utf-8") as fh:
fh.write(body)
print(" [%d/%d] %s %d 字" % (idx, len(articles), title[:36], len(content)))

print("[4/4] 生成汇总 ...")
with open(os.path.join(outdir, "articles.json"), "w", encoding="utf-8") as fh:
json.dump(records, fh, ensure_ascii=False, indent=2)

records.sort(key=lambda r: (r["publish"] or r["date"], r["title"]))
lines = ["# cinn.cn %s 文章汇总" % month, "",
"共 %d 篇,抓取时间 %s" % (len(records), time.strftime("%Y-%m-%d %H:%M:%S")), ""]
for r in records:
lines.append("- [%s](%s) %s(%d 字)" % (r["publish"] or r["date"], r["url"], r["title"], r["words"]))
with open(os.path.join(outdir, "index.md"), "w", encoding="utf-8") as fh:
fh.write("\n".join(lines))

print("\n完成:%d 篇,HTTP 请求 %d 次" % (len(records), fetcher.requests))
print("输出目录: %s" % outdir)
print("汇总文件: %s" % os.path.join(outdir, "index.md"))

if __name__ == "__main__":
main()