本文實(shí)例講述了Python實(shí)現(xiàn)的爬蟲刷回復(fù)功能。分享給大家供大家參考,具體如下:
最近閑的無(wú)聊,就想著去看看爬蟲,順著爬蟲順利的做到了模擬登錄、刷帖子等等,這里簡(jiǎn)要說(shuō)一下。
使用Python2.7寫的爬蟲,對(duì)某論壇做模擬登陸和刷帖子、回復(fù)等等,由于之前是沒(méi)有接觸過(guò)爬蟲,這次之后感覺(jué)爬蟲很強(qiáng)大,能做很多事,先來(lái)貼幾張圖。
由于論壇不讓使用相同的文字,所以調(diào)用了笑話的api,達(dá)到不同文字的目的。
該論壇使用的是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())
先要分析該網(wǎng)站登錄地址,登錄需要的參數(shù),如上代碼
獲得cookie之后,分析該論壇的回復(fù)參數(shù),該論壇采用的是post提交,需要有帖子id,回復(fù)內(nèi)容等等,分析之后得到如下代碼
代碼先加載文件里面的cookie,然后調(diào)用了haha這個(gè)笑話api,當(dāng)然我已經(jīng)將這個(gè)api的json進(jìn)行了處理,這里只要笑話內(nèi)容就行。
'''回復(fù)帖子'''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 "當(dāng)前第" + str(num) + "" + "次回帖" print("當(dāng)前帖子id" + str(i)) sleep(1)
發(fā)帖子代碼:
'''發(fā)帖子(普通帖子或者加懸賞分的帖子:并不是懸賞板塊的帖子)'''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())
新聞熱點(diǎn)
疑難解答
圖片精選