文章前言
前段时间,这么说应该是去年,想利用树莓派做个爬虫服务器,然后发布到WordPress上,搜索找到eqblog
博客上有个Python3下WordPress 数据库发布文章的类,所以试了一下非常不错,做个记录,有需要的可以试试看。
这个代码只使用在Python3上,在使用之前需要安装PyMsql
库:
pip3 install PyMySQL
代码部分
class wordpress_post:
def __init__(self,tittle,content):
self.tittle=tittle
self.content=content
def mysql_con(self):
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='pwd', db='wordpress', charset='utf8') #将这里换为你的数据库地址
return conn
def up(self):
times=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
sql="INSERT INTO wp_posts(post_author,post_date,post_content,post_title,post_excerpt,post_status,comment_status,ping_status,post_name,to_ping,pinged,post_modified,post_content_filtered,post_parent,menu_order,post_type,comment_count) VALUES ('1','%s','%s','%s','','publish','open','open','%s','','','%s','','0','0','post','0')" % (str(times),str(self.content),str(self.tittle),str(self.tittle),str(times))
return sql
def cat(self,ids,cat):
sql="INSERT INTO wp_term_relationships(object_id,term_taxonomy_id,term_order) VALUES (%s,%s,'0')"%(ids,cat)
return sql
def close_mysql(self,cursor,conn):
conn.commit()
cursor.close()
conn.close()
[tip type="tip success" ]
记得上面代码的conn
变量中设置你的数据库地址和用户名密码
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='pwd', db='wordpress', charset='utf8') #将这里换为你的数据库地址
使用方法
a=wordpress_post(str(t),wz_content) #这里第一个参数是标题 第二个是文章内容
conn=a.mysql_con()
cursor = conn.cursor()
c=a.up()
effect_row = cursor.execute(c)
new_id = cursor.lastrowid #这里是记录文章id以便设置文章的分类
d=a.cat(new_id,'1')
effect_row = cursor.execute(d)
a.close_mysql(cursor,conn)
其实自己可以结合上面的代码利用多线程做个爬虫是非常方便的。
不错不错,可以拿来做爬虫了。