用python脚本批量导入excel表格文件里的内容到WordPress

功能:读取excel表格的内容发布到wordpress , 表格里的第一列为标题,第二列为内容。

这个适合有一定代码基础的小伙伴来操作,先在主题目录下的functions.php内添加如下代码:

这段代码是为了接收提交过来的数据,并发布成文章,默认发布到了未分类目录,如需要其他目录请自行修改

if(isset($_GET['wbox']) && $_GET['wbox'] == 'update'){
	
	$title = $_POST['title'];
	$content = $_POST['content'];
	$new_post = array(
    'post_title' => $title,
    'post_content' => $content,
    'post_status' => 'publish',
    'post_author' => 1, // 用户 ID
    'post_type' => 'post',
	);


	// 插入文章并获取新文章的 ID
	$post_id = wp_insert_post( $new_post );


	if ( is_wp_error( $post_id ) ) {
    // 如果插入失败,输出错误信息
    	echo $post_id->get_error_message();
	} else {
    	die("ok");
	}
}
```

然后需要用到的python代码如下:

```python
import pandas
import requests, re
import threading

from threading import Thread, Lock

api_url = "http://你的网址/?wbox=update"
excel_file = "表格文件.xlsx"


def put_post(id, title, content, num=0):
    try:
        res = requests.post(api_url, data={'title': title, "content": content},
                            timeout=30)
        if res.status_code == 200:
            res.text == "ok" and print(id + 1, title, "发布成功")
    except Exception:
        num += 1
        print("请求出错,再试", num)
        num < 2 or put_post(id, title, content, num)


lock_obj = threading.RLock()  # 防止共享数据错乱


def worker():
    while True:

        try:
            lock_obj.acquire()  # 上锁
            post_data = post_list.pop(0)
        except Exception:
            lock_obj.release()  # 解锁
            break
        lock_obj.release()  # 解锁
        put_post(post_data[0], post_data[1], post_data[2])


if __name__ == '__main__':

    thread_num = int(input("请输入线程数量:"))

    # read_excel 两个参数  sheet_name = '读取的工作表名,默认第一个', skiprows = 跳过的行数
    wd = pandas.read_excel(excel_file)
    post_list = []
    for i in range(wd.shape[0]):
        post_list.append([i, wd.iloc[i, 0], wd.iloc[i, 1]])

    # 函数式创建线程
    lst = [Thread(target=worker) for _ in range(thread_num)]
    for i in lst:
        i.start()
    for i in lst:
        i.join()
    print("执行完毕")
```

支持多线程提交,线程数太多了的话,可能会把服务器数据库跑挂,具体看服务器性能了。

本文分享至:`[https://blog.wbox8.com/notes/16412042614.html](https://blog.wbox8.com/notes/16412042614.html)`
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值