上次我們使用selenium模擬登錄袋鼠供應鏈的網(wǎng)站,今天我們使用同樣的方法來登錄京東商城,換湯不換藥。
1.引入相關模塊
from selenium import webdriver
import sys
import requests
import time
import re
import os
from lxml import etree
2.引入selenium package, 建立webdriver對象
sel = webdriver.Chrome()
loginurl = 'https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F'
# open the login in page
sel.get(loginurl)
3.通過xpath找到賬戶登錄,模擬點擊
try:
sel.find_element_by_xpath(
"http://div[@class='w']/div[@class='login-form']/div[@class='login-tab login-tab-r']").click()
print('click success!')
except:
print('click error!')
4.通過xpath找到賬號框,密碼框進行輸入
try:
sel.find_element_by_xpath(
"http://div[@class='mc']/div[@class='form']/form[@id='formlogin']/div[@class='item item-fore1']/input[@id='loginname']").send_keys('******')
print('user success!')
except:
print('user error!')
time.sleep(1)
# sign in the pasword
try:
sel.find_element_by_xpath(
"http://div[@class='mc']/div[@class='form']/form[@id='formlogin']/div[@id='entry']/input[@id='nloginpwd']").send_keys('*******')
print('pw success!')
except:
print('pw error!')
time.sleep(1)
5.通過xpath找的登錄按鈕,模擬點擊
try:
sel.find_element_by_xpath(
"http://div[@class='form']/form[@id='formlogin']/div[@class='item item-fore5']/div[@class='login-btn']/a[@id='loginsubmit']").click()
print('click success!')
except:
print('click error!')
time.sleep(3)
6.通過對象的方法獲取當前訪問網(wǎng)站的session cookie
# get the session cookie
cookie = [item["name"] + "=" + item["value"] for item in sel.get_cookies()]
# print cookie
cookiestr = ';'.join(item for item in cookie)
print(cookiestr)
7.將獲取到的cookiestr存儲到headers中
# 偽造User-Agent請求頭
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'cookie': cookiestr
}