Hongmu Notes
Home Language Notes python batch publish articles to wordpress sub-theme
Language Notes python

python batch publish articles to wordpress sub-theme

python batch publish articles to wordpress sub-theme

Capture network packets using Fiddler, then write a Python script to process them.

After collecting the articles, you can simply publish them on your website – it's very convenient.

However, this script is only suitable for use on this website.

The code is currently placed here as a backup.

import requests
import pandas as pd
import re
import time
import os
import json

# ---------- 配置 ----------
EXCEL_PATH = r"C:\Users\18102\Downloads\jietu\1.xlsx"
AJAX_URL = "https://www.4s5.cn/wp-admin/admin-ajax.php"
CATEGORY_ID = 41

EXCEL_DIR = os.path.dirname(EXCEL_PATH)
PUBLISHED_LOG = os.path.join(EXCEL_DIR, "published.txt")
LOG_PATH = os.path.join(EXCEL_DIR, "publish.log")

# 完整的 Cookie(请确保有效)
COOKIE_STRING = ""

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest",
    "Referer": "https://www.4s5.cn/newposts",
    "Origin": "https://www.4s5.cn",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Cookie": COOKIE_STRING,
}

RECOMMENDED_ARTICLES = [
    ("1790", "PbootCMS 安全运维完全指南"),
    ("1788", "pbootcms源码安装教程,后台密码,页面空白处理"),
    ("1785", "pbootcms伪静态设置教程"),
]

# ---------- 辅助函数 ----------
def extract_id_and_title(filename):
    match = re.match(r'^(\d{4})_(.+?)\.zip$', filename)
    if match:
        return int(match.group(1)), match.group(2)
    return None, filename

def build_post_content(desc, site_id):
    if desc and isinstance(desc, str) and len(desc.strip()) > 10:
        sentences = [s.strip() for s in desc.split('。') if s.strip()]
        desc_html = ''.join([f'<p>{s}。</p>' for s in sentences])
    else:
        desc_html = '<p>这是一款优质的PbootCMS网站模板,适合各类企业建站需求。模板设计美观,功能完善,欢迎下载使用。</p>'

    img_url = f"https://www.4s5.cn/wp-content/uploads/{site_id:04d}.com.png"
    img_html = f'<h3>模板展示</h3><p><img src="{img_url}" alt="模板截图"></p>'

    install_html = '''
    <h3>安装说明</h3>
    <p>网站后台:/admin.php</p>
    <p>账号:admin</p>
    <p>密码:admin</p>
    '''

    password_html = '<p>解压密码:www.4s5.cn</p>'

    rec_html = '<h3>相关文章</h3><ul>'
    for post_id, title in RECOMMENDED_ARTICLES:
        rec_html += f'<li><a href="https://www.4s5.cn/archives/{post_id}.html" target="_blank">{title}</a></li>'
    rec_html += '</ul>'

    return desc_html + img_html + install_html + password_html + rec_html

# ---------- 日志记录 ----------
def log_response(site_id, response_text, success_flag=False):
    with open(LOG_PATH, 'a', encoding='utf-8') as f:
        f.write(f"=== Site {site_id:04d} ===\n")
        f.write(response_text + "\n")
        f.write("--- 标记为成功 ---\n" if success_flag else "--- 标记为失败 ---\n")
        f.write("\n")

# ---------- 已发布记录管理 ----------
def load_published_ids():
    if not os.path.exists(PUBLISHED_LOG):
        return set()
    with open(PUBLISHED_LOG, 'r', encoding='utf-8') as f:
        return {line.strip() for line in f if line.strip()}

def save_published_id(site_id):
    with open(PUBLISHED_LOG, 'a', encoding='utf-8') as f:
        f.write(f"{site_id:04d}\n")

# ---------- 主程序 ----------
def main():
    published_ids = load_published_ids()
    print(f" 已发布 {len(published_ids)} 篇。")

    df = pd.read_excel(EXCEL_PATH)
    df = df.sort_values('站点id').reset_index(drop=True)
    print(f" Excel 共 {len(df)} 条记录。")

    auto_mode = False  # 是否自动发布模式

    for idx, row in df.iterrows():
        site_id = int(row['站点id'])
        site_id_str = f"{site_id:04d}"

        if site_id_str in published_ids:
            print(f"⏭️ 站点 {site_id_str} 已发布,跳过。")
            continue

        filename = row['文件名']
        link = row['链接']
        desc = row.get('描述', '')

        sid, title_part = extract_id_and_title(filename)
        if sid is None:
            print(f"❌ 文件名格式错误:{filename},跳过。")
            continue

        if not auto_mode:
            print(f"\n 当前准备发布:{site_id_str} - {title_part}")
            print("   选项:")
            print("     按 回车  → 发布")
            print("     输入 2   → 跳过(不记录)")
            print("     输入 3   → 退出脚本")
            print("     输入 4   → 自动发布(此后不再询问)")
            choice = input("请选择:").strip()

            if choice == '3':
                print(" 用户选择退出。")
                break
            elif choice == '4':
                auto_mode = True
                print(" 已切换为自动发布模式,将连续发布所有剩余站点。")
                # 当前站点继续发布(不跳过)
            elif choice == '2':
                print(f"⏭️ 跳过站点 {site_id_str}。")
                continue
            elif choice == '':
                # 回车,发布
                pass
            else:
                print("输入无效,按回车键将视为发布。")

        # ---------- 执行发布 ----------
        title = f"{title_part} {sid:04d}"
        content = build_post_content(desc, site_id)

        pay_download = {
            "link": link,
            "more": "解压密码:www.4s5.cn",
            "copy_key": "解压密码",
            "copy_val": "www.4s5.cn",
            "name": "百度网盘下载",
            "class": ""
        }

        data = {
            "post_title": title,
            "post_content": content,
            "category[]": CATEGORY_ID,
            "tags": "",
            "zibpay_s": "on",
            "posts_zibpay[pay_modo]": "0",
            "posts_zibpay[pay_price]": "0",
            "posts_zibpay[vip_1_price]": "0",
            "posts_zibpay[vip_2_price]": "0",
            "posts_zibpay[pay_download][0][link]": pay_download["link"],
            "posts_zibpay[pay_download][0][more]": pay_download["more"],
            "posts_zibpay[pay_download][0][name]": pay_download["name"],
            "posts_zibpay[pay_download][0][copy_key]": pay_download["copy_key"],
            "posts_zibpay[pay_download][0][copy_val]": pay_download["copy_val"],
            "posts_zibpay[pay_download][0][class]": pay_download["class"],
            "posts_id": "0",
            "action": "posts_save"
        }

        try:
            resp = requests.post(AJAX_URL, headers=HEADERS, data=data, timeout=30)
            resp_text = resp.text
            try:
                result = resp.json()
            except:
                result = {}

            # 成功判断
            success = False
            if result.get('posts_id'):
                success = True
            elif result.get('error') == False:
                success = True
            elif '已发布' in result.get('msg', ''):
                success = True

            log_response(site_id, resp_text, success_flag=success)

            if success:
                post_id = result.get('posts_id', '未知')
                print(f"✅ 发布成功!站点 {site_id_str} -> 文章ID {post_id}")
                save_published_id(site_id)
                published_ids.add(site_id_str)
            else:
                error_msg = result.get('msg', '未知错误')
                print(f"❌ 发布失败!站点 {site_id_str},错误:{error_msg}")
        except Exception as e:
            print(f"❌ 异常:{e},站点 {site_id_str}")
            with open(LOG_PATH, 'a', encoding='utf-8') as f:
                f.write(f"=== Site {site_id:04d} ===\n")
                f.write(f"EXCEPTION: {str(e)}\n\n")

        time.sleep(1.5)

    print(f"\n 脚本执行完毕。已发布 {len(load_published_ids())} 篇。")

if __name__ == "__main__":
    main()
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Import " requests" could not be resolved from source

Import " requests" could not be resolved from source Language Notes python

This error occurred when using Pylance, a Python language server. Among them, " Import " requests" could not be resolved from source" This error message indicates that the requests module is referenced in your code, but Pylance cannot find the location of the module from the source. The possible reason is that you don't have an …
👁 1771
Reinstall Python and requests libraries

Reinstall Python and requests libraries Language Notes python

If you meet " Import " requests" could not be resolved from source" You can try reinstalling Python and requests libraries. First, you need to uninstall the current Python and requests libraries. On Windows systems, you can use the command prompt …
👁 439
WARNING: Skipping requests as it is not installed.

WARNING: Skipping requests as it is not installed. Language Notes python

This error message indicates that your Python environment lacks the requests library, and this library is called in your code, so Python cannot execute your code normally. The solution to this problem is to install the requests library. You can use the pip command on the command line to install: pip install requests If you are using Python3, you can use the pip3 command …
👁 2100
Python reported an error. What is the reason? AttributeError: partially initialized module ' openai'  has no attribute ' Completion' (most likely due to a circular import)

Python reported an error. What is the reason? AttributeError: partially initialized module ' openai' has no attribute ' Completion' (most likely due to a circular import) Language Notes python

This error prompt indicates that there is a problem when importing the openai module and the specific Completion attribute, which is probably caused by circular import. The reason for this error may be that two or more modules in your code are imported from each other, forming a circular dependency. For example, module A imports module B, and module B imports module A.. Cyclic import will cause the module not to initialize correctly when loading, thus …
👁 656
How does python package and run on Windows?

How does python package and run on Windows? Language Notes python

The most common way to package and run Python programs on Windows is to use PyInstaller. PyInstaller is a free and cross-platform Python application packaging tool, which can package Python code and its dependent libraries into an independent executable file, making it possible to run Python programs on systems without Python interpreters installed. The following is to make …
👁 300
What programming software is good for python development?

What programming software is good for python development? Language Notes python

There are many programming softwares developed by Python. The following are some commonly used Python integrated development environments (IDE) and editors: PyCharmPyCharm is an integrated development environment developed by JetBrains, which is specially designed for Python developers. PyCharm is powerful and provides a series of advanced functions such as code completion, debugging, version control, code refactoring, etc., which can help developers improve their work …
👁 175

Recommended reading

Responsive premium leather goods and high-end luggage website template – 0416

Responsive premium leather goods and high-end luggage website template – 0416 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the premium leather goods and high-end luggage industry. Its sophisticated and fashionable design perfectly showcases leather goods products, brand stories, design concepts, and customisation services. It enables leather goods brands to showcase their products online and attract consumers who value a quality lifestyle. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 55
(PC+WAP) Blue Cable Tray Website – PbootCMS Template; Cable, Steel Structure, Hardware, and Machinery Website Source Code Download – 0567

(PC+WAP) Blue Cable Tray Website – PbootCMS Template; Cable, Steel Structure, Hardware, and Machinery Website Source Code Download – 0567 Practical Collection pbootcms Template

A PbootCMS Blue Universal Template designed for the cable tray and steel structure hardware machinery industries, supporting access via both PC and WAP devices. Its clear and practical design is ideal for showcasing products such as cable trays and bus ducts. This template helps cable tray manufacturing enterprises create professional branded official websites and product display platforms online. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: w...
👁 52
Responsive Advertising Design Creative Agency Website Template 1123

Responsive Advertising Design Creative Agency Website Template 1123 Practical Collection Yiyou template

An eyouCMS responsive website template designed for advertising design and creative agencies. Its innovative visual design style is ideal for showcasing advertising design works, creative case studies, brand strategy initiatives, and service offerings. This template helps advertising agencies demonstrate their professional expertise online and attract brand clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YouyouCMS...
👁 46
How can you limit the size of the ibtmp1 file in MySQL so that it doesn't keep growing indefinitely?

How can you limit the size of the ibtmp1 file in MySQL so that it doesn't keep growing indefinitely? Summary of pitfalls

In MySQL, the temporary tablespace file `ibtmp1` is a dynamically evolving file whose actual size is determined on the fly based on actual usage requirements. If this file is not properly managed or constrained, it may continuously grow in size and eventually consume a significant amount of disk space. Therefore, you can use the following method to limit the size of the `ibtmp1` file: add `innodb_temp_data_file` to the `my.cnf` file...
👁 379
Custom Suit and Professional Workwear Website Template 0073

Custom Suit and Professional Workwear Website Template 0073 Practical Collection Yiyou template

An EyouCMS website template designed for the suit and professional attire customization industry. Its premium, professional design effectively showcases custom suit-making, professional wear design, and corporate group purchasing services. This template helps clothing customization brands attract corporate clients online and highlight their craftsmanship and case studies. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 46
(Adaptive mobile version) pbootCMS Steel Processing Website Template – Download source code for steel cutting and steel sales websites – 0227

(Adaptive mobile version) pbootCMS Steel Processing Website Template – Download source code for steel cutting and steel sales websites – 0227 Practical Collection pbootcms Template

This is an adaptive, mobile-friendly PbootCMS website template designed for steel processing and steel sales businesses. Its robust, professional design effectively showcases steel product specifications, processing services, and inventory information. It helps steel trading enterprises demonstrate their online presence and attract construction and manufacturing clients. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 44