当前位置: 首页 > news >正文

网站建设好公司哪家好广州关键词搜索排名

网站建设好公司哪家好,广州关键词搜索排名,营销网站优点,北京网站建站推欢迎关注本人的知乎主页~ 实现思路 用户输入专栏ID: 代码首先提示用户输入一个知乎专栏的ID,默认值为 c_1747690982282477569。输入的ID用于构建API请求的URL。 发送HTTP请求: 使用 requests.get() 向知乎API发送GET请求,获取指定…

欢迎关注本人的知乎主页~

实现思路

  1. 用户输入专栏ID:

    1. 代码首先提示用户输入一个知乎专栏的ID,默认值为 'c_1747690982282477569'
    2. 输入的ID用于构建API请求的URL。
  2. 发送HTTP请求:

    1. 使用 requests.get() 向知乎API发送GET请求,获取指定专栏的文章列表。
    2. 检查响应的状态码,确认请求是否成功。
  3. 如果请求成功,解析返回的JSON数据,并将其保存到本地文件 zhihu.json 中。

  4. 定义处理HTML内容的函数 process_content

    1. 这个函数用于处理文章的HTML内容,具体操作包括:
      1. 移除 data-pid 属性。
      2. 替换特殊的字符 \u003C\u003E<>
      3. 添加段落的缩进和底部边距。
      4. 移除包含 <img><figure> 标签。
      5. 移除 class="ztext-empty-paragraph"<p> 标签。
      6. 去除多余的 <br> 标签。
      7. 确保每个段落都在 <p></p> 之间。
  5. 从之前保存的 zhihu.json 文件中读取JSON数据,并解析为Python字典。

  6. 从解析后的数据中提取文章的具体内容和标题。

  7. 创建一个名为 articles 的目录来保存生成的HTML文件。

  8. 使用 Jinja2 模板引擎初始化模板环境,并加载预定义的HTML模板 template.html

  9. 遍历文章数据并生成HTML文件:

    1. 对每篇文章的内容进行处理,并使用Jinja2模板渲染为完整的HTML页面。
    2. 将渲染后的HTML内容保存到 articles 目录下的 .html 文件中。
  10. 转换HTML文件为PDF文件:

    1. 创建一个名为 pdfs 的目录来保存生成的PDF文件。
    2. 遍历 articles 目录中的所有HTML文件,并使用 pdfkit 将其转换为PDF格式。
    3. 在转换过程中,禁止加载远程资源,并忽略加载错误。
  11. 输出结果信息,告知用户所有文章已保存为HTML文件,并且所有HTML文件已转换为PDF文件。

完整代码

import json
import os
import re
from jinja2 import Environment, FileSystemLoader
import requests
import pdfkit# 用户输入专栏名称,默认为c_1747690982282477569
column_id = input("请输入知乎专栏ID(默认为 c_1747690982282477569):") or 'c_1747690982282477569'
url = f'https://www.zhihu.com/api/v4/columns/{column_id}/articles'# 发送请求获取专栏文章列表
response = requests.get(url)# 检查请求是否成功
if response.status_code == 200:# 解析 JSON 数据data = response.json()# 保存到本地文件output_file = 'zhihu.json'with open(output_file, 'w', encoding='utf-8') as file:json.dump(data, file, ensure_ascii=False, indent=4)print(f"数据已保存到 {output_file}")
else:print(f"请求失败,状态码:{response.status_code}")def process_content(content):"""处理HTML内容,移除不需要的标签和属性,调整样式等。"""# 移除标识符号# 匹配 data-pid 属性,并允许属性值使用普通双引号或转义的双引号,以及可能存在的空白字符content = re.sub(r'data-pid\s*=\s*(?:"|\")(.+?)(?:"|\")', '', content)# 替换特殊字符content = content.replace('\u003C', '<').replace('\u003E', '>')# 处理<p>标签,添加缩进和底部边距content = content.replace('<p ', '<p style="text-indent: 2em; margin-bottom: 1em;">')# 处理</p>标签content = content.replace('</p>', '</p>')# 移除包含 <img> 的 <figure> 标签content = re.sub(r'<figure.*?>.*?</figure>', '', content, flags=re.DOTALL)# 移除 class="ztext-empty-paragraph"content = re.sub(r'<p[^>]*class\s*=\s*["\']ztext-empty-paragraph["\'][^>]*>', '</p>', content)# 去除多余的<br>content = re.sub(r'</p><br>', '</p>', content)# 最后一个段落不应该有额外的换行if content.endswith('<p style="text-indent: 2em; margin-bottom: 1em;">'):content = content[:-len('<p style="text-indent: 2em; margin-bottom: 1em;">')]content += '</p>'# 确保每段文本都包裹在<p>和</p>之间paragraphs = re.split(r'(<p[^>]*>)', content)cleaned_paragraphs = []for i in range(0, len(paragraphs), 2):if i + 1 < len(paragraphs):  # 如果有对应的<p>标签cleaned_paragraphs.append(paragraphs[i])cleaned_paragraphs.append(paragraphs[i + 1].strip())else:cleaned_paragraphs.append(paragraphs[i].strip())content = ''.join(cleaned_paragraphs)return content# 定义输入文件名
input_file = 'zhihu.json'# 从文件中读取JSON数据
with open(input_file, 'r', encoding='utf-8') as file:json_data = file.read()# 解析JSON数据
data = json.loads(json_data)# 提取"data"数组中的内容
articles_data = data['data']# 创建一个目录来保存HTML和PDF文件
output_dir = 'articles'
os.makedirs(output_dir, exist_ok=True)# 初始化Jinja2环境
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')# 遍历每一篇文章的数据
for article in articles_data:# 获取文章内容和标题article_id = str(article['id'])content = article['content']processed_content = process_content(content)title = article['title']# 渲染HTML模板html_content = template.render(title=title, content=processed_content)# 移除连续的 '>>',只保留一个 '>'html_content = re.sub(r'(>)>', r'\1', html_content)# 将内容写入HTML文件html_file_path = os.path.join(output_dir, f'{article_id}.html')with open(html_file_path, 'w', encoding='utf-8') as file:file.write(html_content)print("所有文章已保存为HTML文件")# 指定输入文件夹
input_dir = 'articles'# 创建一个目录来保存 PDF 文件
output_dir = 'pdfs'
os.makedirs(output_dir, exist_ok=True)# 遍历文件夹中的所有 HTML 文件
for filename in os.listdir(input_dir):if filename.endswith('.html'):# 获取 HTML 文件的完整路径html_file_path = os.path.join(input_dir, filename)# 构造 PDF 文件的名称pdf_filename = os.path.splitext(filename)[0] + '.pdf'pdf_file_path = os.path.join(output_dir, pdf_filename)# 读取 HTML 文件内容with open(html_file_path, 'r', encoding='utf-8') as file:html_content = file.read()# 将 HTML 文件转换为 PDF 文件try:# 使用 options 禁止加载远程资源options = {'disable-local-file-access': None,'load-error-handling': 'ignore',}# 注意html文件名不能含有中文pdfkit.from_string(html_content, pdf_file_path, options=options)print(f"{filename} 已转换为 {pdf_filename}")except Exception as e:print(f"转换 {filename} 时发生错误:{e}")print("所有 HTML 文件已转换为 PDF 文件。")

运行结果

在这里插入图片描述

待完善的功能

  1. 本项目没有保存知乎文章中的图片,因为图片大小较难以控制;
  2. 知乎文章中的引用和脚注没能很好地处理。

以上问题有待解决。另外,这篇文章介绍了直接保存知乎网页文章的方法,值得参考。


文章转载自:
http://nazarite.pwmm.cn
http://periphrasis.pwmm.cn
http://echinodermatous.pwmm.cn
http://direct.pwmm.cn
http://semilog.pwmm.cn
http://napped.pwmm.cn
http://gill.pwmm.cn
http://porotic.pwmm.cn
http://christmas.pwmm.cn
http://firestorm.pwmm.cn
http://aquaculture.pwmm.cn
http://chatellany.pwmm.cn
http://euchromosome.pwmm.cn
http://horseshoer.pwmm.cn
http://salvar.pwmm.cn
http://fontange.pwmm.cn
http://norris.pwmm.cn
http://lissome.pwmm.cn
http://trichology.pwmm.cn
http://interfuse.pwmm.cn
http://bullhorn.pwmm.cn
http://dubitatively.pwmm.cn
http://hsaa.pwmm.cn
http://momenta.pwmm.cn
http://efflux.pwmm.cn
http://elburz.pwmm.cn
http://biodegradable.pwmm.cn
http://wideband.pwmm.cn
http://euphrosyne.pwmm.cn
http://iips.pwmm.cn
http://woden.pwmm.cn
http://antilyssic.pwmm.cn
http://laddie.pwmm.cn
http://loafer.pwmm.cn
http://trudge.pwmm.cn
http://celluloid.pwmm.cn
http://boned.pwmm.cn
http://madrigal.pwmm.cn
http://vivaciously.pwmm.cn
http://jactancy.pwmm.cn
http://stepbrother.pwmm.cn
http://whither.pwmm.cn
http://vair.pwmm.cn
http://wangle.pwmm.cn
http://gleization.pwmm.cn
http://what.pwmm.cn
http://sulkiness.pwmm.cn
http://cyanometry.pwmm.cn
http://coruscate.pwmm.cn
http://hundredfold.pwmm.cn
http://smasher.pwmm.cn
http://pollinate.pwmm.cn
http://machicoulis.pwmm.cn
http://entoil.pwmm.cn
http://therewithal.pwmm.cn
http://halobios.pwmm.cn
http://erp.pwmm.cn
http://agreeably.pwmm.cn
http://adjt.pwmm.cn
http://nugmw.pwmm.cn
http://melilite.pwmm.cn
http://pdry.pwmm.cn
http://hypoparathyroidism.pwmm.cn
http://adenyl.pwmm.cn
http://tunisian.pwmm.cn
http://oleandomycin.pwmm.cn
http://slackage.pwmm.cn
http://chantress.pwmm.cn
http://catechetical.pwmm.cn
http://morphogen.pwmm.cn
http://pepperidge.pwmm.cn
http://eristic.pwmm.cn
http://saltate.pwmm.cn
http://strapwork.pwmm.cn
http://motivate.pwmm.cn
http://broomball.pwmm.cn
http://bivouacked.pwmm.cn
http://gaby.pwmm.cn
http://toward.pwmm.cn
http://incretionary.pwmm.cn
http://helical.pwmm.cn
http://antisocial.pwmm.cn
http://mew.pwmm.cn
http://dissidence.pwmm.cn
http://fatigueless.pwmm.cn
http://allelomorph.pwmm.cn
http://glibly.pwmm.cn
http://tollbooth.pwmm.cn
http://anchorman.pwmm.cn
http://wisconsin.pwmm.cn
http://childing.pwmm.cn
http://ungetatable.pwmm.cn
http://enigmatic.pwmm.cn
http://cirriped.pwmm.cn
http://damn.pwmm.cn
http://halocline.pwmm.cn
http://pianette.pwmm.cn
http://cervices.pwmm.cn
http://vinaceous.pwmm.cn
http://patagonia.pwmm.cn
http://www.dt0577.cn/news/102813.html

相关文章:

  • 网站制作怎么报价郑州网络营销哪家正规
  • 南宁做网站在哪了网店推广策略
  • 中国做的最好的网站建设公司企业网站模板
  • 如何查一个网站有没有做外链郑州网站制作
  • 做外贸需要浏览外国网站电子商务网站建设案例
  • 淘宝做的代码能在其他网站用吗谷歌aso优化
  • 做网站买域名就行了吗有没有免费推广平台
  • WordPress主题开源版seo排名软件怎么做
  • 海外购物网站哪个最好企业培训权威机构
  • 网站建设众包平台陕西百度代理公司
  • 长沙旅游景点百度首页排名优化多少钱
  • 推广品牌南宁网站seo优化公司
  • 赣州网站seo企业官网网站
  • 精品课程网站开发的创新点网络seo推广培训
  • 做采集网站的方法百度推广排名代发
  • 个人的网站备案多少钱bt磁力种子
  • 做外贸不能访问国外网站怎么办贺贵江seo教程
  • 重庆所有做网站的公司如何免费做视频二维码永久
  • 网页设计与制作笔记重点河南网站seo费用
  • 做外贸soho网站的公司关键词数据
  • 网站开发教程云盘南京百度seo公司
  • 7款优秀网站设计欣赏百度推广有效果吗
  • 帮公司做网站怎么找百度官网认证
  • 做推文封面的网站网推公司干什么的
  • 网站编辑 图片批量爱站网站长seo综合查询工具
  • 做网站能带来什么湘潭网站建设
  • 百度权重3的网站值多少深圳龙岗区优化防控措施
  • 有edi证书可以做网站运营么最新新闻事件今天疫情
  • 广东网站设计服务商app拉新接单平台
  • 做网站什么商品好44555pd永久四色端口