运用Python实现WordPress网站大规模自动化发布文章

时间:2022-04-25
本文章向大家介绍运用Python实现WordPress网站大规模自动化发布文章,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

很多用WordPress建站的朋友都有这样的苦恼,网站建好了,没有时间自己写文章,慢慢就荒废了,还有的朋友在浏览器收集好多喜欢的博客网站地址,因为收集的网址太多太杂,从此也很少点开看。其实只要几行代码我们就可以完全利用Python和WordPress建一个属于自己的文章抓取站点。主要是运用python newspaper xmlrpc 模块编写实现网页爬虫,通过正则匹配爬取网页内容后,用xmlrpc自动发布到WordPress部署的网站。然后采用crond定时抓取。

第一部分:抓取目标页面的文章

#得到html的源码
def gethtml(url1):
    #伪装浏览器头部
    headers = {
       'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
}

    req = urllib2.Request(
    url = url1,
    headers = headers
    )
    html = urllib2.urlopen(req).read()
    return html
#得到目标url源码
code1 = gethtml('https://www.baidu.com')#示例
#提取内容
content1 = re.findall('<h2 class="title"><a href="(.*)">(.*)</a></h2>',code1)#示例
#追加记录采集来的内容
f1 = open('contents1.txt','a+')
#读取txt中的内容
exist1 = f1.read()

第二部分:通过xmlrpc发送文章到WordPress

def sends():
    for i in range(len(content1)):
        u=content1[i][0]
        url='https://www.baidu.com'+u
        a=Article(url,language='zh')
        a.download()
        a.parse()
        dst=a.text
        title=a.title

        #链接WordPress,输入xmlrpc链接,后台账号密码
        wp = Client('http://www.python-cn.com/xmlrpc.php','username','password')
        post = WordPressPost()
        post.title = title
        post.content = dst
        post.post_status = 'publish'
        #发送到WordPress
        wp.call(NewPost(post))
        time.sleep(3)
        print 'posts updates'

最后,通过crontab定时运行程序,采集指定文章发送的WordPress

0 12 * * 2 /usr/bin/python /home/workspace/python-cn/python-cn.py