python模擬瀏覽器登入人人網,並使用代理IP和傳送表單資料

Thinkgamer_gyt發表於2015-09-28

Python模擬登入人人網,並使用代理IP

#__author__ = 'Administrator'
#encoding=utf-8
import urllib2,urllib
import cookielib
from bs4 import BeautifulSoup
#登入的url
hosturl = "http://www.renren.com"

#這裡是要將賬號和密碼等資訊要傳送到的url,我用的是WSExploer抓包
posturl = "http://www.renren.com/ajaxLogin/login"

#生成cookies
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
#opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
#ullib2.install_opener(opener)

#開啟登陸介面,獲取cookie,並將該cookie儲存下來
h = urllib2.urlopen(hosturl)

#設定使用代理
proxy = {'http':'120.197.234.164:80'}
proxy_support = urllib2.ProxyHandler(proxy)
# opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler(debuglevel=1))
opener = urllib2.build_opener(cookie_support,proxy_support,urllib2.HTTPHandler)
urllib2.install_opener(opener)

#構造頭,這方法和上邊獲取posturl方法一樣
headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0/',
    'Referer':'http://www.renren.com/'
}

#傳送的資料,同上
postdata={
    'email':'xxxxxxxxxxx',         #使用者名稱
    'password':'xxxxxxxxxx'   #密碼
}

#將資料進行編碼
postdata = urllib.urlencode(postdata)

#構造一個請求訊息
request = urllib2.Request(posturl,postdata,headers)
print "requests:%s" % request

#傳送一個請求訊息
response = urllib2.urlopen(request)
text = response.read()
print "text:%s" %text

listvalue = text.split(",")

#獲取人人登入的主頁
href = listvalue[1].split(":")[2]
#print href[:-2]
renrenhttp = "http:" + href[:-2]
print "renrenhttp:%s" % renrenhttp

#print urllib2.urlopen(renrenhttp).read()
page = urllib2.urlopen(renrenhttp).read()

soup = BeautifulSoup(page)
print soup.title

上述程式碼中同時使用了代理ip和模擬登入,若不使用代理ip只需修改如下

為:

即可

相關文章