最近閑的無聊,就想着去看看爬蟲,順着爬蟲順利的做到了模擬登錄、刷帖子等等,這里簡要說一下。
使用Python2.7寫的爬蟲,對某論壇做模擬登陸和刷帖子、回復等等,由於之前是沒有接觸過爬蟲,這次之后感覺爬蟲很強大,能做很多事,先來貼幾張圖。
由於論壇不讓使用相同的文字,所以調用了笑話的api,達到不同文字的目的。
該論壇使用的是cookie,所以先去獲取一下cookie,順便將cookie寫到文件里面。
''' 獲取cookie ''' def get_cookie(login_data, url, testurl=None): filename = "cookie" cookie = cookielib.MozillaCookieJar(filename) hadler = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(hadler) post_data = urllib.urlencode( {'logname': 123456, "logpass": "123456", "action": "login", }) url = 'http://*****.me/waplogin.aspx' opener.open(url, post_data) cookie.save(ignore_discard=True, ignore_expires=True) print("獲取成功") # print(opener.open(testurl).read())
先要分析該網站登錄地址,登錄需要的參數,如上代碼
獲得cookie之后,分析該論壇的回復參數,該論壇采用的是post提交,需要有帖子id,回復內容等等,分析之后得到如下代碼
代碼先加載文件里面的cookie,然后調用了haha這個笑話api,當然我已經將這個api的json進行了處理,這里只要笑話內容就行。
''' 回復帖子 ''' def post_reply(): filename = "cookie" cookie = cookielib.MozillaCookieJar(filename) cookie.load(filename, ignore_discard=True, ignore_expires=True) handler = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(handler) num=0 for i in range(216255, 800000): num = num + 1 huifu = urllib.urlencode( {'sendmsg': 0, "content": str(haha(num)), "action": "add", "id": str(i), "classid": 177}) gradeUrl = 'http://******.me/bbs/book_re.aspx' result = opener.open(gradeUrl) print result.read() print "當前第" + str(num) + "" + "次回帖" print("當前帖子id" + str(i)) sleep(1)
發帖子代碼:
''' 發帖子(普通帖子或者加懸賞分的帖子:並不是懸賞板塊的帖子) ''' def post_articles(book_title, book_content, classid=177, sendmoney=0): filename = "cookie" cookie = cookielib.MozillaCookieJar(filename) cookie.load(filename, ignore_discard=True, ignore_expires=True) handler = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(handler) post_articles = urllib.urlencode( {'sendmsg': 0, "book_title": str(book_title), "action": "gomod", "siteid": "1000", "book_content": str(book_content), "classid": classid, "sendmoney": sendmoney}) gradeUrl = 'http://*****.me/bbs/book_view_add.aspx' result = opener.open(gradeUrl, post_articles) print(result.read())
將這些代碼進行進行調用就可以去刷回復了。