这篇文章主要介绍了如何使用selenium和requests组合实现登录页面,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一、在这里selenium的作用
(1)模拟的登录。
(2)获取登录成功之后的cookies
代码
def start_login(self): chrome_options = Options() # 禁止图片加载,禁止推送通知 prefs = { "profile.default_content_setting_values": { "images": 2 }, "profile.default_content_setting_values.notifications": 2 } chrome_options.add_experimental_option("prefs", prefs) if chrome_args().get("headless_flag") == "1": chrome_options.add_argument(chrome_args().get("headless")) chrome_options.add_argument(chrome_args().get("nogpu")) chrome_options.add_argument(chrome_args().get("noinfobars")) chrome_options.add_argument(chrome_args().get("max_windows")) chrome_options.add_argument(self.Proxy_server) driver = webdriver.Chrome(chrome_options=chrome_options) try: get_logger().info("start login.....") try: # login info self.login_name = self.loginInfo.get("login_id") self.password = aes_cbc_decrypt(self.loginInfo.get("login_pwd")) except Exception: get_logger().error("cant get login info,here are detals".format(traceback.format_exc())) wait = WebDriverWait(driver, 30) print(u"start login in") driver.get(self.login_url) try: login_id = wait.until( eccd.presence_of_element_located( (By.XPATH, self.Id_xpath)) ) login_id.send_keys(self.login_name) login_id.send_keys(Keys.ENTER) password = wait.until( eccd.presence_of_element_located( (By.XPATH, self.pwd_xpath)) ) password.send_keys(self.password) submit = wait.until( eccd.presence_of_element_located( (By.XPATH, self.login_btn_xpath)) ) submit.click() # login signal #判断是否显示 右上角是否显示用户名 login_ok = wait.until( eccd.presence_of_element_located( (By.XPATH, self.login_ok_xpath)) ) try: #判断登录成功 if login_ok: get_logger().info("get user name successful:"+u"{}".format(login_ok.text)) try: get_weibo_info=driver.find_element_by_xpath(self.forward_home_page) except: driver.get(self.first_page) forward_home_page_ok = wait.until( eccd.presence_of_element_located( (By.XPATH, self.forward_home_page)) ) forward_home_page_ok.click() time.sleep(5) self.first_page=driver.current_url get_logger().info("get homepage successful,url is {}".format(driver.current_url)) cookies = driver.get_cookies() # 导出cookie get_logger().info("get cookies") get_fansnum_ok= wait.until( eccd.presence_of_element_located( (By.XPATH, self.follow_xpath)) ) self.get_followfanshome(driver) get_logger().info("get_followfanshome ok") self.home_page_source=driver.page_source driver.close() # 关闭chrome #获取主页的 # 如果需要保存cookies self.write_cookie(cookies) get_logger().info("get cookies,login ok") return cookies else: raise RuntimeError('login failed') except: get_logger().error("login failed") return None except: if driver is not None: driver.close() except Exception as e: if driver is not None: driver.close() get_logger().error("dbs operation error,here are details:{}".format(traceback.format_exc()))
新闻热点
疑难解答