如何通过Pywikibot判断索引模板的页码参数是否为空?
嘿,这个重复写入页码的问题我熟,给你几个实用的解决思路和代码示例,帮你避免重复拼接页码的情况:
核心思路
要解决这个问题,关键是先获取页面的现有内容,判断|Number of pages=参数是否已经填充了非空值,如果已经有值就跳过写入逻辑,只有当参数为空或者不存在时,再执行填充操作。
具体实现代码
这里结合pywiki的用法,给你两种可行的实现方式:
方式1:字符串查找判断(适合简单模板结构)
#!/usr/bin/env python # -*- coding: utf-8 -*- import pywiki # 初始化站点(请确保已完成pywiki的登录配置) site = pywiki.Site('zh', 'wikisource') target_page = site.page('你的目标书籍索引页标题') # 获取页面当前的完整内容 current_content = target_page.get() # 定义要检查的参数标识 page_param = '|Number of pages=' # 检查参数是否存在并已填充值 if page_param in current_content: # 定位参数值的起始和结束位置 param_start = current_content.find(page_param) + len(page_param) # 找到下一行的换行符,作为参数值的结束标记 param_end = current_content.find('\n', param_start) if param_end == -1: param_end = len(current_content) # 提取并去除首尾空白 existing_page_num = current_content[param_start:param_end].strip() if existing_page_num: print("页码参数已经填充,跳过本次操作") exit() # 到这里说明参数为空或不存在,执行填充逻辑 target_page_num = "67" # 替换成你的目标页码 # 根据页面结构选择插入/替换方式: # 情况1:参数已存在但为空,直接替换空值 if page_param in current_content: updated_content = current_content.replace(f"{page_param}\n", f"{page_param}{target_page_num}\n") else: # 情况2:参数不存在,假设插入到Book模板的结尾前(根据实际页面结构调整) template_end_pos = current_content.find('}}') if template_end_pos != -1: updated_content = current_content[:template_end_pos] + f"\n{page_param}{target_page_num}" + current_content[template_end_pos:] else: # 备用:直接追加到页面末尾 updated_content = current_content + f"\n{page_param}{target_page_num}" # 保存页面,添加编辑摘要 target_page.text = updated_content target_page.save("自动填充书籍页码:首次写入,避免重复")
方式2:正则表达式匹配(适合复杂模板结构)
如果页面模板参数格式多变(比如参数前后有空格),用正则表达式能更精准匹配:
#!/usr/bin/env python # -*- coding: utf-8 -*- import pywiki import re site = pywiki.Site('zh', 'wikisource') target_page = site.page('你的目标书籍索引页标题') current_content = target_page.get() # 用正则匹配页码参数,允许参数和值之间有任意空格 param_pattern = r'\|Number of pages\s*=\s*(.*?)\n' match_result = re.search(param_pattern, current_content) if match_result: existing_value = match_result.group(1).strip() if existing_value: print("页码已存在,无需重复写入") exit() # 填充逻辑和上面一致,这里省略重复部分 target_page_num = "67" # ...(同方式1的填充代码)
注意事项
- 请根据目标页面的实际模板结构调整填充逻辑,比如如果页面用的是其他模板,需要修改插入参数的位置。
- 测试时可以先使用
page.save()的dry_run=True参数(如果pywiki支持),先预览修改内容再正式保存,避免误操作。
内容的提问来源于stack exchange,提问作者info-farmer
相关产品推荐
相关产品推荐

