python模拟登录淘宝直通车_Python实现的淘宝直通车数据抓取(1)
最近幫一個朋友做一個抓取淘寶直通車數據的小項目,感覺ython比較適合寫爬蟲程序,決定使用Python來做程序。
首先是登陸程序,因為淘寶的登陸校驗很復雜,所以不能直接使用命令行的形式輸入賬號密碼。查閱資料后,發現可以使用Selenium的自動測試框架,決定用這個框架實現登陸。
首先下載一個純凈版的firefox瀏覽器,放到主目錄下,然后用python打開瀏覽器:
def openbrowser_login():
binary=FirefoxBinary(os.getcwd()+'/Firefox/Firefox.exe')
profile=FirefoxProfile()
profile.set_preference("browser.cache.disk.enable",False)
profile.set_preference("browser.cache.offline.enable",False)
driver=webdriver.Firefox(firefox_binary=binary,firefox_profile=profile)
driver.get('http://zhitongche.taobao.com/')
while(True):
if(len(driver.window_handles)>1):
print('檢測到頁面跳轉!')
driver.switch_to.window(driver.window_handles[1]);
time.sleep(3)
driver.get(driver.current_url)
time.sleep(5)
break;
else:
time.sleep(2)
cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
cookiestr=';'.join(item for item in cookie)
try:
driver.quit()
except Exception as e:
pass
return cookiestr
實現的方式就是先去文件目錄下找到firefox的啟動文件,然后使用瀏覽器打開淘寶直通車的登陸頁,程序每隔兩秒檢測一次頁面,如果發現新開了額外的標簽,就認為是登錄成功,這時把頁面的cookie保存下來并返回。打開瀏覽器時同時設置了一些屬性,profile是瀏覽器屬性設置文件,這里將瀏覽器緩存功能關閉。
下面是實現檢查登陸的函數:
def check_login(cookiestr):
print('開始登陸驗證!')
url='https://i.taobao.com/my_taobao.htm'
headers= {
'Host':'i.taobao.com',
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
# 'Accept-Encoding':'gzip, deflate',
'Referer' :'https://www.taobao.com',
'Content-Type': 'application/x-www-form-urlencoded',
'Connection' : 'Keep-Alive',
'Cookie' : cookiestr,
'Cache-Control':'max-age=0',
}
request=urllib.request.Request(url,headers=headers)
try:
response=urllib.request.urlopen(request)
# print(response.geturl())
if(response.geturl()==url):
print('登陸驗證通過!')
return True
except Exception as e:
print(e)
print('登陸驗證失敗!請重新登陸!')
return False
然后是檢查淘寶直通車權限,如果檢查權限通過,就將cookie文件保存下來方便下次使用:
def check_subway(cookiestr):
print('開始淘寶直通車驗證!')
url='http://subway.simba.taobao.com/bpenv/getLoginUserInfo.htm'
headers= {
'Host':'subway.simba.taobao.com',
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
'Accept':'application/json, text/javascript, */*; q=0.01',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection' : 'Keep-Alive',
'Cookie' : cookiestr,
'Origin':'http://subway.simba.taobao.com',
'Cache-Control':'max-age=0',
'X-Requested-With':'XMLHttpRequest'
}
request=urllib.request.Request(url,headers=headers)
data={'_referer':'/tools/insight/index'}
postdata=urllib.parse.urlencode(data).encode('utf-8')
try:
response=urllib.request.urlopen(request,data=postdata)
string=response.read().decode()
parse=json.loads(string)
if(parse['code']=='200'):
print('淘寶直通車驗證通過!您當前以登陸')
fp=open('cookie','wt')
fp.write(cookiestr)
fp.close()
print('登陸cookie已經保存!')
return parse['result']['token']
except Exception as e:
print(e)
print('淘寶直通車驗證失敗!請重新登陸!')
return False
在主函數中,程序將優先加載cookie文件,cookie失效或沒有cookie文件時打開瀏覽器進行登陸:
#主函數
if(os.path.exists('cookie')):
print('檢測到cookie文件!將使用cookie登陸!')
fp=open('cookie','r')
cookiestr=fp.read()
fp.close()
else:
cookiestr=openbrowser_login()
while(True):
if(check_login(cookiestr)):
token=check_subway(cookiestr)
if(token!=False):
break;
cookiestr=openbrowser_login()
總結
以上是生活随笔為你收集整理的python模拟登录淘宝直通车_Python实现的淘宝直通车数据抓取(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微型计算机可避免强磁场干扰,微型计算机测
- 下一篇: python怎样导入scrapy_(Py