Python 模拟淘宝登录的两种方法

时间:2024-04-15 16:47:24

方法一、urllib的post登录

import urllib  
import urllib2  
import cookielib   
  
def taobao(username,password):    
    cj = cookielib.CookieJar()    
    print cj  
    post_data = urllib.urlencode(    
        {     
         \'TPL_password\':password,     
         \'TPL_username\':username,    
         })  
      
    path = \'https://login.taobao.com/member/login.jhtml\'    
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))    
     
    opener.addheaders = [(\'User-agent\', \'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13\')]     
        
    urllib2.install_opener(opener)    
    req = urllib2.Request(path,post_data)    
      
    #try login    
    conn = urllib2.urlopen(req)    
    html = conn.read().decode(\'gbk\',\'ignore\')  
    print cj  
    print html  
      
      
taobao(\'username\',\'password\')    
print \'OK\'    

方法二:通过selenium模拟浏览器登录

from selenium import webdriver  
driver = webdriver.Chrome()  
#driver = webdriver.Firefox()  
                 
  
driver.get(\'https://login.taobao.com/member/login.jhtml\')  
  
driver.find_element_by_xpath(\'//*[@id="J_QRCodeLogin"]/div[5]/a[1]\').click()  
driver.find_element_by_id("TPL_username_1").clear()  
driver.find_element_by_id("TPL_password_1").clear()  
driver.find_element_by_id("TPL_username_1").send_keys(\'xxx\')  
driver.find_element_by_id("TPL_password_1").send_keys(\'xxx\')  
  
driver.find_element_by_id("J_SubmitStatic").click()  
  
#driver.get_cookies()取得cookie  
cookie = "; ".join([item["name"] + "=" + item["value"] +"\n" for item in driver.get_cookies()])  
print cookie  

参考http://blog.****.net/u010352695/article/details/40660133

http://www.cnblogs.com/linxiyue/p/3537557.html