使用Python给Wordpress发布文章,我们可以通过两种方式实现:
1、通过xmlrpc,详细操作可以看这里
2、直接操作数据库。
其实大多数情况下,使用第一种方法就可以满足需求了,可是有时候xmlrpc却无法满足我们的需要,比如我之前就遇到过:网站中安装了WP Job Manager插件,发布的文章类型变成了“job_listing”,写入数据的时候,job_listing_category和location这两个字段总是无法成功写入数据。所以,自己今天又研究了一下python直接操作Wordpress数据库发布文章的功能。由于自己对SQL语法不熟悉,花了我大半天时间才折腾成功。
一、建立虚拟环境
virtualenv wp_database cd wp_database/Scripts activate
需要安装的库:
mysqlclient==1.4.2.post1
二、查询数据库
代码如下:
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 连接数据库 db = MySQLdb.connect("localhost", "root", "", "01py", charset='utf8' ) cursor = db.cursor() # SQL sql = "SELECT * FROM wp_posts WHERE post_author =1" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: db.rollback() data = cursor.fetchall() for row in data: ID = row[0] author = row[1] postdate = row[2] content = row[4] title = row[5] # ´òÓ¡½á¹û print("ID是:{}\n作者:{}\n发布日期:{}\n标题:{}\n内容是:{}\n ".format(ID,author,postdate,title,content)) db.close()
执行结果:
三、发布文章
最终代码
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb import time db = MySQLdb.connect("localhost", "root", "", "01py", charset='utf8' ) cursor = db.cursor() #数据来源 post_content = "python这是文章内容测试" post_title = "title标题测试New" post_name = "must_be_only_english" times=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) # SQL 语句 sql = """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) 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)) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() post_id = cursor.lastrowid if post_id >0: print("成功插入数据,数据编号为{}".format(post_id)) except: db.rollback() db.close()
效果展示:
需要解决的问题:发布的文章“分类目录”那一栏是空的。
看了一下,wordpress的分类目录牵涉到下面两个表:
wp_terms:存储每个目录、标签
wp_term_relationships:存储每个文章、链接和对应分类的关系
所以如果要将上面的代码用于项目的话,还需要继续完善。
另外,如果要实现标签功能的话,除了上面2张表,还需要修改wp_term_taxonomy这张表。
另外,学习python操作数据库可以看这里。
Python操作Mysql实例教程手册(带书签)
四、如何发布文章缩略图?
from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import GetPosts, NewPost from wordpress_xmlrpc.methods.users import GetUserInfo from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.compat import xmlrpc_client from wordpress_xmlrpc.methods import media, posts def make_post(content): wp = Client('https://yoursite.com/xmlrpc.php', 'user', 'pass') post = WordPressPost() post.title = content['title'] post.content = content['body'] post.terms_names = { 'post_tag': ['AutoBlogger', 'BotPosted'], 'category': ['News', 'Update'] } # Lets Now Check How To Upload Media Files filename = '1.jpg' data = { 'name': '1.jpg', 'type': 'image/jpeg' # Media Type } # Now We Have To Read Image From Our Local Directory ! with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] # Above Code Just Uploads The Image To Our Gallery # For Adding It In Our Main Post We Need To Save Attachment ID post.thumbnail = attachment_id post.post_status = 'publish' post.id = wp.call(posts.NewPost(post)) # Set Default Status For Post .i.e Publish Default Is Draft # We Are Done With This Part 🙂 Lets Try To Run It print("Sucessfully Posted To Our Blog !")
参考:https://www.youtube.com/watch?v=W0ksqbNBRoc
原载:蜗牛博客
网址:http://www.snailtoday.com
尊重版权,转载时务必以链接形式注明作者和原始出处及本声明。