The previous section describes the browser's common methods, involving the use of cookies, this section describes how to use cookies for landing system, where the request module is used, we first use the request module, requesting the login address to log in, the successful login to obtain the cookie value, It is then added to the browser via Add_cookie, leaving the system in a logged-in state. It is important to note that the format of the cookie returned by request requests cannot be passed directly to the Add_cookie method, so conversions are required here.
#you need to note the difference here, press and hold the format to convert#request returns the format of the cookie{'Phpsessid':'Alvrh1i2h7joj2il2jn3sh7up1','UID':' -'}#The format of the cookie required by the Selenium method{'value':'Alvrh1i2h7joj2il2jn3sh7up1','HttpOnly': False,'Domain':'yingxiao.chewumi.com','name':'Phpsessid','Secure': False,'Path':'/'}
Take a look at the example below to log in and jump to the Circle details page
#-*-coding:utf-8-*-Import TimeImportRequests fromSeleniumImportWebdriverdefget_system_cookies (Url,account,password):" "access cookies via the request login system" "cookieslist=[] Data= {"username": Account,"passwd":p Assword} roomsession=requests. Session () roomsession.post (Url,data=data) Loadcookies=Requests.utils.dict_from_cookiejar (roomsession.cookies) forCookiename,cookievalueinchloadcookies.items (): Cookies={} cookies['name'] =cookiename cookies['value'] =cookievalue cookieslist.append (cookies)returncookieslistdefis_login_status_succeed (Driver):" "decide whether to log in or not, log in via cookie" "loginurl='http://yingxiao.chewumi.com/login.php' #Login AddressAccount =' Account' #Account NumberPassword ='Password' #PasswordDriver.get ('http://yingxiao.chewumi.com/index.php')#test for login status if 'Please login' inchDriver.page_source:#determine if landing is a landing page forCookiesinchGet_system_cookies (Loginurl,account,password):#If the login interface gets a cookieDriver.add_cookie (Cookie)#add cookies and log in via cookies returnDriverdefrequest_circle_details (driver,requesturl):" "Test Jump Circle Details" "is_login_status_succeed (Driver) driver.get (requesturl) Verifyfield= Driver.find_element_by_xpath ('/html/body/div/div/div[2]/h1'). Text#Get page title Try: assertVerifyfield = ='Circle Details' return 'Test Pass' exceptAssertionerror as E:return 'Test not passed'" "Test the effect" "Requesturl='http://yingxiao.chewumi.com/list.php?page=1'Driver=Webdriver. Chrome () Driver.maximize_window ()Print(Request_circle_details (Driver,requesturl)) Driver.get (Requesturl) time.sleep (2) Driver.quit ()
Through the results show that we do not operate the login status, directly into the circle details to the page.
Python selenium-webdriver via Cookie (11)