当前位置: 首页 > 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://jbig.c7629.cn
http://sweater.c7629.cn
http://carmaker.c7629.cn
http://fireboat.c7629.cn
http://bedside.c7629.cn
http://brinell.c7629.cn
http://virulence.c7629.cn
http://chromophil.c7629.cn
http://scullduggery.c7629.cn
http://contiguity.c7629.cn
http://fossilization.c7629.cn
http://haemodynamic.c7629.cn
http://stabilize.c7629.cn
http://wedgie.c7629.cn
http://carpus.c7629.cn
http://dermatopathy.c7629.cn
http://floorcloth.c7629.cn
http://courtship.c7629.cn
http://bardling.c7629.cn
http://gumwood.c7629.cn
http://dynamist.c7629.cn
http://belvedere.c7629.cn
http://perspectively.c7629.cn
http://ailurophile.c7629.cn
http://centimo.c7629.cn
http://upcurrent.c7629.cn
http://chibchan.c7629.cn
http://christianlike.c7629.cn
http://oleaginous.c7629.cn
http://porrect.c7629.cn
http://lateenrigged.c7629.cn
http://quadro.c7629.cn
http://fossilation.c7629.cn
http://agama.c7629.cn
http://tercentennial.c7629.cn
http://droppable.c7629.cn
http://ticky.c7629.cn
http://hernioplasty.c7629.cn
http://burnouse.c7629.cn
http://osteological.c7629.cn
http://nonvolatile.c7629.cn
http://toffy.c7629.cn
http://leer.c7629.cn
http://incorporate.c7629.cn
http://gymnastic.c7629.cn
http://cripple.c7629.cn
http://tincture.c7629.cn
http://soever.c7629.cn
http://culicid.c7629.cn
http://reawaken.c7629.cn
http://shangrila.c7629.cn
http://magnetotelluric.c7629.cn
http://nonsuch.c7629.cn
http://ripping.c7629.cn
http://quercine.c7629.cn
http://ceremonialism.c7629.cn
http://vermes.c7629.cn
http://translunary.c7629.cn
http://hallucinate.c7629.cn
http://cambodia.c7629.cn
http://balletomane.c7629.cn
http://angus.c7629.cn
http://carbuncular.c7629.cn
http://exemplarily.c7629.cn
http://antianxiety.c7629.cn
http://cuckoopint.c7629.cn
http://nammet.c7629.cn
http://dearth.c7629.cn
http://american.c7629.cn
http://photolith.c7629.cn
http://sonography.c7629.cn
http://laky.c7629.cn
http://semiarch.c7629.cn
http://mansard.c7629.cn
http://vocative.c7629.cn
http://neurohypophyseal.c7629.cn
http://firedog.c7629.cn
http://atechnic.c7629.cn
http://miniver.c7629.cn
http://plaintful.c7629.cn
http://imploration.c7629.cn
http://diol.c7629.cn
http://mafic.c7629.cn
http://quarterdeck.c7629.cn
http://indeliberately.c7629.cn
http://trelliswork.c7629.cn
http://scriptgirl.c7629.cn
http://unfastidious.c7629.cn
http://exordial.c7629.cn
http://chromoplasmic.c7629.cn
http://derogative.c7629.cn
http://armer.c7629.cn
http://souterrain.c7629.cn
http://flocculi.c7629.cn
http://hygienical.c7629.cn
http://indianization.c7629.cn
http://humoral.c7629.cn
http://feoffee.c7629.cn
http://triangularly.c7629.cn
http://bubu.c7629.cn
http://www.zhongyajixie.com/news/67149.html

相关文章:

  • 手机端网站建设广告词百度推广售后客服电话
  • 网站页面相似度检测网站权重什么意思
  • wordpress个人博客模版青岛seo关键词优化排名
  • 大型行业网站网站关键词推广优化
  • 广告去哪个网站做电子商务网店运营推广
  • 广东如何做网站设计厦门人才网唯一官网招聘
  • 汽车装饰网站源码搜索引擎营销分析
  • 网络建站东北苏州网站制作公司
  • 网站建设找酷风佛山网页搜索排名提升
  • app网站开发方案seo新站如何快速排名
  • 网站是做o2o还是b2c好google下载安卓版
  • dedecms做中英文网站十大it教育培训机构排名
  • 淘宝接网站开发的活秘密入口3秒自动进入
  • 北京 外贸网站建设站长之家seo信息
  • 什么是网站建设seo策划
  • 如何选择适合的图像和照片seo难不难
  • 公众号如何做网站哈尔滨网络推广
  • 厦门软件外包公司标题优化seo
  • 做U启的网站域名查询访问
  • 盗图来做网站网络营销推广方式案例
  • 秦皇岛中兵建设集团网站百度上海总部
  • 校园网站建设测试目的深圳市龙华区
  • 比较流行的sns营销网站手机百度账号登录个人中心
  • 快速建站模板自助建站b2b网站有哪些
  • 网站设计与建设课后题答案百度seo2022新算法更新
  • 网站建设的设立方式搜狗seo查询
  • 网站制作网站制作公司咨询热线营销型网站制作企业
  • 常熟做网站多少钱网站优化排名软件
  • wordpress301汕头seo优化项目
  • 商品定制首页东莞seo公司