运用Python实现WordPress网站*敏*感*词*自动化发布文章(附源码版)
优采云 发布时间: 2022-05-08 14:43运用Python实现WordPress网站*敏*感*词*自动化发布文章(附源码版)
很多用WordPress建站的朋友都有这样的苦恼,网站建好了,没有时间自己写文章,慢慢就荒废了,还有的朋友在浏览器收集好多喜欢的博客网站地址,因为收集的网址太多太杂,从此也很少点开看。其实只要几行代码我们就可以完全利用Python和WordPress建一个属于自己的文章抓取站点。主要是运用python newspaper xmlrpc 模块编写实现网页爬虫,通过正则匹配爬取网页内容后,用xmlrpc自动发布到WordPress部署的网站。然后采用crond定时抓取。
代码开源在github:运用Python实现WordPress网站*敏*感*词*自动化发布文章
第一部分:抓取目标页面的文章
#得到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('(.*)',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
后续橙哥将详细写出newspaper抓取文章、WordPress xmlrpc配置等细节和代码的具体解释,具体请关注微信公众号:Python中文社区
Python中文社区(),致力于成为国内最好的Python开发者学习交流平台,这里有关于Python的*敏*感*词*最新消息,每日推送有趣有料的技术干货和社区动态。欢迎长按以下二维码扫描关注!