模拟登录(二)

上次我们使用selenium模拟登录袋鼠供应链的网站,今天我们使用同样的方法来登录京东商城,换汤不换药。

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(
        "//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(
        "//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(
        "//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(
        "//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.通过对象的方法获取当前访问网站的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
}

你可能感兴趣的:(模拟登录(二))