Home >  > Python操作WordPress数据库发布文章

Python操作WordPress数据库发布文章

0

使用Python给Wordpress发布文章,我们可以通过两种方式实现:
1、通过xmlrpc,详细操作可以看这里

2、直接操作数据库。

其实大多数情况下,使用第一种方法就可以满足需求了,可是有时候xmlrpc却无法满足我们的需要,比如我之前就遇到过:网站中安装了WP Job Manager插件,发布的文章类型变成了“job_listing”,写入数据的时候,job_listing_category和location这两个字段总是无法成功写入数据。所以,自己今天又研究了一下python直接操作Wordpress数据库发布文章的功能。由于自己对SQL语法不熟悉,花了我大半天时间才折腾成功。

一、建立虚拟环境

1virtualenv wp_database
2cd wp_database/Scripts
3activate

需要安装的库:
mysqlclient==1.4.2.post1

二、查询数据库
代码如下:

1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3 
4import MySQLdb
5 
6# 连接数据库
7db = MySQLdb.connect("localhost", "root", "", "01py", charset='utf8' )
8 
9 
10cursor = db.cursor()
11 
12# SQL
13sql = "SELECT * FROM wp_posts WHERE post_author =1"
14 
15try:
16    # Execute the SQL command
17    cursor.execute(sql)
18    # Commit your changes in the     database
19    db.commit()
20except:
21    db.rollback()
22 
23 
24data = cursor.fetchall()
25for row in data:
26      ID = row[0]
27      author = row[1]
28      postdate = row[2]
29      content = row[4]
30      title = row[5]
31      # ´òÓ¡½á¹û
32      print("ID是:{}\n作者:{}\n发布日期:{}\n标题:{}\n内容是:{}\n ".format(ID,author,postdate,title,content))     
33 
34db.close()

执行结果:

三、发布文章
最终代码

1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3 
4import MySQLdb
5import time
6 
7 
8db = MySQLdb.connect("localhost", "root", "", "01py", charset='utf8' )
9 
10 
11cursor = db.cursor()
12 
13#数据来源
14post_content = "python这是文章内容测试"
15post_title = "title标题测试New"
16post_name = "must_be_only_english"
17 
18 
19times=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
20 
21 
22# SQL 语句
23sql = """INSERT INTO wp_posts(post_author,post_date,post_date_gmt,post_content,post_title,post_excerpt,post_status,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_content_filtered,post_parent,guid,menu_order,post_type,post_mime_type,comment_count)
24         VALUES ('1','%s','%s','%s','%s','','publish','open','open','','%s','','','%s','%s','','0','http://127.0.0.1/01wp/?p=20','0','post','','0')""" % (str(times),str(times),str(post_content),str(post_title),str(post_name),str(times),str(times))
25 
26 
27try:
28    # Execute the SQL command
29    cursor.execute(sql)
30    # Commit your changes in the     database
31    db.commit()
32    post_id = cursor.lastrowid
33    if post_id >0:
34      print("成功插入数据,数据编号为{}".format(post_id))   
35except:
36    db.rollback()
37 
38db.close()

效果展示:


需要解决的问题:发布的文章“分类目录”那一栏是空的。
看了一下,wordpress的分类目录牵涉到下面两个表:

wp_terms:存储每个目录、标签
wp_term_relationships:存储每个文章、链接和对应分类的关系

所以如果要将上面的代码用于项目的话,还需要继续完善。

另外,如果要实现标签功能的话,除了上面2张表,还需要修改wp_term_taxonomy这张表。

另外,学习python操作数据库可以看这里。
Python操作Mysql实例教程手册(带书签)

四、如何发布文章缩略图?

1from wordpress_xmlrpc import Client, WordPressPost
2from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
3from wordpress_xmlrpc.methods.users import GetUserInfo
4from wordpress_xmlrpc import Client, WordPressPost
5from wordpress_xmlrpc.compat import xmlrpc_client
6from wordpress_xmlrpc.methods import media, posts
7 
8 
9def make_post(content):
10    wp = Client('https://yoursite.com/xmlrpc.php',
11                'user', 'pass')
12    post = WordPressPost()
13    post.title = content['title']
14    post.content = content['body']
15    post.terms_names = {
16        'post_tag': ['AutoBlogger', 'BotPosted'],
17        'category': ['News', 'Update']
18    }
19    # Lets Now Check How To Upload Media Files
20    filename = '1.jpg'
21    data = {
22        'name': '1.jpg',
23        'type': 'image/jpeg'  # Media Type
24    }
25    # Now We Have To Read Image From Our Local Directory !
26    with open(filename, 'rb') as img:
27        data['bits'] = xmlrpc_client.Binary(img.read())
28        response = wp.call(media.UploadFile(data))
29    attachment_id = response['id']
30 
31    # Above Code Just Uploads The Image To Our Gallery
32    # For Adding It In Our Main Post We Need To Save Attachment ID
33    post.thumbnail = attachment_id
34    post.post_status = 'publish'
35    post.id = wp.call(posts.NewPost(post))
36    # Set Default Status For Post .i.e Publish Default Is Draft
37 
38    # We Are Done With This Part 🙂 Lets Try To Run It
39    print("Sucessfully Posted To Our Blog !")

参考:https://www.youtube.com/watch?v=W0ksqbNBRoc

原载:蜗牛博客
网址:http://www.snailtoday.com
尊重版权,转载时务必以链接形式注明作者和原始出处及本声明。

暧昧帖

本文暂无标签

发表评论

*

*