https://zhuanlan.zhihu.com/p/93643523
时间: 2025-03-16 20:14:37 浏览: 11
要获取知乎专栏文章的具体内容,可以通过网络爬虫技术来实现。然而,在实际操作之前需要注意的是,任何自动化工具访问网站都应遵循目标站点的 robots.txt
文件规定以及相关法律法规[^2]。
以下是将知乎专栏文章下载并转换成Markdown文件的一个通用流程说明:
文章抓取与处理
为了能够读取指定ID的文章(如93643523),可以采用Python编写脚本完成这一过程。此过程中会涉及HTML解析、特殊字符转义及格式调整等工作[^3]。
HTML内容预处理
定义了一个名为process_content()的方法用来清理原始网页中的杂项元素,使其更适合进一步加工成为结构化的文档形式。主要执行如下几类变更:
- 清理掉无意义的数据属性data-pid;
- 把Unicode编码表示的小于号(\u003C)大于号(\u003E),替换成标准实体符号(<>);
- 统一设置段落样式规则——增加首行缩进同时保留适当间距;
- 去除非必要图片容器标签
及其内部嵌套图像标记 ;
- 删除空白占位用途节点;
- 合并连续换行符
至合理位置;最后确认所有正文部分均被包裹在合法配对的之中。
from bs4 import BeautifulSoup
def process_content(html):
soup = BeautifulSoup(html, 'html.parser')
# Remove data-pid attributes.
for tag in soup.find_all(True):
if 'data-pid' in tag.attrs:
del tag['data-pid']
# Replace special characters.
html = str(soup).replace('\u003C', '&lt;').replace('\u003E', '&gt;')
soup = BeautifulSoup(html, 'html.parser')
# Add indentation and bottom margin to paragraphs.
for p in soup.find_all('p'):
new_p = soup.new_tag("p", style="text-indent: 2em; margin-bottom: 1rem;")
new_p.string = ''.join(map(str,p.contents))
p.replace_with(new_p)
# Remove <figure> tags containing images.
figures = soup.find_all('figure')
for fig in figures:
img_tags = fig.find_all('img')
if len(img_tags)>0:
fig.decompose()
# Remove empty paragraph placeholders.
empties=soup.select('p.ztext-empty-paragraph')
for e in empties:
e.extract()
# Clean up extra line breaks.
brs = soup.find_all('br')
for i in range(len(brs)-1,-1,-1):
br=brs[i]
next_sibbling=br.next_sibling
while isinstance(next_sibbling,str)==False or (isinstance(next_sibbling,str)and not next_sibilling.strip()):
if isinstance(next_sibiling,'Tag') and next_sibiling.name=='br':
next_sibiling.decompose()
elif isinstance(next_sibiling,NavigableString):
break;
else :
pass
return str(soup.body)
转化为Markdown格式
一旦完成了上述初步整理之后,则可继续调用第三方库比如pandoc或者himalaya把修正后的HTML字符串映射到对应的Markdown语法之上[^4]。
pip install pandoc pyhimalaya
import subprocess
def convert_to_markdown(html_content):
command=['pandoc','-f','html','-t','markdown_strict']
result=subprocess.run(command,input=html_content.encode(),stdout=subprocess.PIPE)
markdown=result.stdout.decode().strip()
return markdown
最终得到的结果就可以存储下来供后续分享或存档之用了。
相关推荐


















