一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

用 Doubao-Seed-Evolving + Python 免费开发网页正文提取工具(实战教程)

时间:2026-07-29 12:26:03 编辑:袖梨 来源:一聚教程网

一、先定需求再选择技术

目标:给定一个网页 URL,得到正文 Markdown,其中不再包含导航/广告/侧边栏。

技术选型:

  • readability(readability-lxml)做正文去噪
  • markdownify 把清洗后的 HTML 转 Markdown
  • 预清理由 BeautifulSoup 负责
  • 客户端渲染站点交给 Playwright

Doubao-Seed-Evolving 在一次对话中生成了初版代码,以下整理其中的关键实现和踩坑经历。

二、初版实现

这是我输入提示词后AI给的回答:

节选的核心结构是:

import requestsfrom bs4 import BeautifulSoupfrom readability import Documentimport markdownify as mdDEFAULT_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ..."def fetch_url(url, timeout=15, verify_ssl=True):if not url.startswith(("http://", "https://")):url = "https://" + urlheaders = {"User-Agent": DEFAULT_UA}resp = requests.get(url, headers=headers, timeout=timeout, verify=verify_ssl)resp.raise_for_status()return resp.textdef extract_markdown(html, page_url=""):soup = BeautifulSoup(html, "lxml")for tag in soup.find_all(["script", "style", "nav", "aside", "footer"]):tag.decompose()doc = Document(str(soup), url=page_url)content_html = doc.summary()return md(content_html, heading_style="ATX", convert=["table", "pre"])

注意:第一版有个坑——markdownify 不能同传 convert 和 strip,否则运行时直接报错。预清理已处理 script/style,所以删掉 strip 即可。这个修复也是模型在看到报错后给出的。

三、三类网站的实际测试

测试结果均如实记录,所选对象是 3 个类型不同的网页:

网站类型结果现象
SSR 类型的技术博客完整保留代码块、语言标注和表格
公众号⚠️标题成为 [no-title],正文则 OK
头条(CSR)正文没有内容,仅剩 [no-title]

三个网页中,一个直接提取成功,一个缺少标题,另一个只剩空壳。初版表现没有框架预设得那么糟,但真实问题反而更值得分析,因为不同网站分别暴露了不同短板。

四、关键修复一:为标题提取设置退化方案

og:title 不在 readability-lxml 的 Document.summary() 读取范围内,它只取 <title>。解析 bug 会被微信文章的标题格式触发,结果是 [no-title]。

修复:先增加语义化标题提取这一层,再执行 extract_markdown。

def extract_title(soup, doc):og = soup.find("meta", property="og:title")if og and og.get("content"):return og["content"].strip()tw = soup.find("meta", attrs={"name": "twitter:title"})if tw and tw.get("content"):return tw["content"].strip()h1 = soup.find("h1")if h1 and h1.get_text(strip=True):return h1.get_text(strip=True)return doc.short_title()

五、关键修复二:客户端渲染站点的空壳

头条这类站点正文由 JS 异步加载,requests 拿到的只是 <div id="root"> 空壳。

修复:引入 --render 参数,先让 Playwright 无头浏览器完成渲染,之后执行提取。

from playwright.sync_api import sync_playwrightdef fetch_rendered(url):with sync_playwright() as p:browser = p.chromium.launch(headless=True)page = browser.new_page()page.goto(url, wait_until="networkidle")html = page.content()browser.close()return html

另:微信/头条图片是懒加载,真实地址在 data-src,需补一段把 data-src 回填到 src,否则全文裂图。

六、最终使用方法

python extract_article.py https://juejin.cn/post/xxx -o article.mdpython extract_article.py https://www.toutiao.com/xxx --render -o toutiao.md

静态站不需要额外依赖,动态站加 --render。

热门栏目