selenium登录豆瓣流程:
1. 进入豆瓣登录页面
2. 切换到**子框架**,定位**用户,密码**输入框. 并输入数据,再**定位登录**按键,点击登录.
3. 返回登录成功后的cookies,
4. 关闭驱动浏览器.
遇到的问题:
- 开始定位登录框总是失败. 程序报错
- ==selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {“method”:“id”,“selector”:“username”} ==
- 找不到 定位元素
- 原因:
- 登录框在 一个iframe中,需要切换到包含登录块的frame中
- 解决方法:
![豆瓣登录页面](https://img-blog.csdnimg.cn/20190402142949410.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2tvbmcwNTBrb25n,size_16,color_FFFFFF,t_70)
from selenium import webdriver
import time
class doubanLogin():
def __init__(self):
self.url = "https://www.douban.com"
self.driver = webdriver.Chrome(r"***")
def login(self):
self.driver.get(self.url)
time.sleep(2)
self.driver.switch_to_frame(self.driver.find_element_by_tag_name('iframe'))
self.driver.find_element_by_xpath("/html/body/div[1]/div[1]/ul[1]/li[2]").click()
username = self.driver.find_element_by_id("username").send_keys("***")
password = self.driver.find_element_by_id("password").send_keys('***')
self.driver.find_element_by_class_name('account-form-field-submit').click()
@property
def get_cookies(self):
cookies = self.driver.get_cookies()
return cookies
def __del__(self):
self.driver.close()
if __name__ == "__main__":
douban = doubanLogin()
douban.login()
print(douban.get_cookies)