python+selenium实现豆瓣网站登录
代码实现
from selenium import webdriver
import time
def main():
chrome_driver = 'C:\xxxxx\Google\Chrome\Application\chromedriver.exe'
driver = webdriver.Chrome(executable_path=chrome_driver)
driver.get("https://www.douban.com/")
time.sleep(5)
curFrame = driver.find_element_by_tag_name("iframe")
#print(curFrame)
time.sleep(5)
#登录表单在页面的框架中中,所以要切换到该框架
driver.switch_to_frame(curFrame)
# 通过使用选择器选择到表单元素进行模拟输入和点击按钮提交
driver.find_element_by_class_name('account-tab-account').click();
time.sleep(5)
#input username and password
driver.find_element_by_id('username').send_keys('XXX');
driver.find_element_by_id('password').send_keys('XXX');
#click login button
driver.find_element_by_css_selector('.account-form-field-submit>.btn').click();
time.sleep(10)
driver.quit()
if __name__== '__main__':
main()
参考代码:python + selenium 实现自动登录网站
问题1:switch_to_frame(当前的iframe)
因为定位元素仅会在当前所处的frame中寻找该元素,所以需要先切换到元素所在的frame下