When we log in to Sina Weibo on a common browser, we do not need to enter an account number and password. This is because the browser itself stores the cookie, which avoids the tediousness of logging in again and entering the password again. To use Selenium, the browser driver must be installed. So just one driver.get_cookies() function can get cookies.
First, we need to simulate logging in to Weibo once:
#Login to Weibo driver = webdriver.Chrome() driver.get('https://weibo.com/') time.sleep(5) #Enter the account number driver.find_element_by_xpath('//input[@id="loginname"]').send_keys('username') #enter password driver.find_element_by_xpath('//input[@name="password"]').send_keys('password') #Click to Login driver.find_element_by_xpath('//a[@class="W_btn_a btn_32px"]').click() time.sleep(5) #get cookies cookie = driver.get_cookies() print (type(cookie)) print (cookie)
At this point, we have obtained the browser's cookie. The cookie is a list of 18 dictionaries, each with 7 elements:
{"domain": ".weibo.com", "expiry": xxxxxxxx, "httpOnly": False, "name": "un", "path": "/", "secure": False, "value": "xxxxxxx"}Then, we just use driver.add_cookie() to add these 18 dictionaries to the driver's cookie.
# 1. Open the webpage driver = webdriver.Chrome() driver.get('http://weibo.com') # 2. Delete cookies driver.delete_all_cookies() # 3. Add the cookie obtained in the previous step cookielist = [{dictionary},....,{dictionary}] for cookie in cookielist: driver.add_cookie(cookie) # Four, refresh the page, you can log in driver.refresh()Give it a try, isn't it much more convenient than Finder to capture packets?