只要十分钟,用Python实现自动化

登陆

要评论当然要能够先进行登陆,采用 requests 库进行处理,尝试能否看到自己的消息列表:

msg_url ="http://msg.csdn.net/" r = requests.get(msg_url,auth=(‘drfish‘,‘password‘))

结果跳转到登陆界面,好的那看一下登陆界面是怎么登陆的,找到表单:

分享图片

发现还有一些隐藏的参数,如lt、excution等,好心的程序猿还写明了不能为什么不能直接认证的原因:缺少流水号,那就多访问一次来获取流水号好了,用 BeautifulSoup 来分析页面内容抓取流水号,同时因为要跨不同的域来进行操作,所以引入session:

msg_url = "http://msg.csdn.net/" login_url = "https://passport.csdn.net/" 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‘} session = requests.session() session.headers.update(headers) r = session.get(login_url) page = BeautifulSoup(r.text,"lxml") authentication = { "username": "drfish","password": "password","lt": page.select("[name=lt]")[0]["value"],"execution": page.select("[name=execution]")[0]["value"],"_eventId": "submit",} r = session.post(login_url,authentication) r2 = session.get(msg_url) print(r2.text)

好了,现在能够得到我的消息信息了,说明已经成功解决登陆问题,那么自动化水军评论应该就近在眼前了。

自动评论

这次学乖了,随便找了篇文章直接查看评论框form:

分享图片

c

在上面登陆代码的基础上进行评论的提交:

blog_url = "http://blog.csdn.net/u013291394/comment/submit?id=50444369" comment = { "comment_content": "水军评论测试","comment_usrId":"531203" } r2 = session.post(blog_url,comment) print(r2.text)

结果返回了 {"result":0,"content":"评论内容没有填写!","callback":null,"data":null} 这样的结果。有点意思,应该是在js中对参数进行了处理。那就把js拉出来看看,网页里搜了一下js文件,有个 comment.js ,就是它了。在上面的form中可以看到提交时调用了subform方法,查看方法如下:

function subform(e) { if (c_doing) return false; var content = $.trim($(editorId).val()); if (content == "") { commentTip("评论内容没有填写!"); return false; } else if (content.length > 1000) { commentTip("评论内容太长了,不能超过1000个字符!"); return false; } var commentId = $("#commentId").val(); commentTip("正在发表评论..."); var beginTime = new Date(); $(editorId).attr("disabled",true); $("button[type=submit]",e).attr("disabled",true); c_doing = true; $.ajax({ type: "POST",url: $(e).attr("action"),data: { "commentid": commentId,"content": content,"replyId": $("#comment_replyId").val(),"boleattohome": $("#boleattohome").val() },success: function (data) { c_doing = false; commentTip(data.content); if (data.result) { var rcommentid=$("#comment_replyId").val() $(editorId).val(‘‘); $("#comment_replyId,#comment_verifycode").val(‘‘); commentscount++; loadList(1,true); $(editorId).attr("disabled",false); $("button[type=submit]",false); commentTip("发表成功!评论耗时:" + (new Date() - beginTime) + "毫秒") 

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...