python使用selenium获取token和session
时间: 2024-05-25 20:05:12 浏览: 19
可以使用Selenium来模拟浏览器登录获取token和session,具体步骤如下:
1. 安装Selenium库
```
pip install selenium
```
2. 下载浏览器驱动
根据自己使用的浏览器类型下载对应的驱动,例如使用Chrome浏览器则需要下载ChromeDriver。下载地址:https://sites.google.com/a/chromium.org/chromedriver/downloads
3. 打开浏览器并登录网站
```python
from selenium import webdriver
# 启动浏览器
driver = webdriver.Chrome('/path/to/chromedriver')
# 打开登录页面
driver.get('https://example.com/login')
# 输入账号密码并提交表单
username_input = driver.find_element_by_name('username')
password_input = driver.find_element_by_name('password')
username_input.send_keys('your_username')
password_input.send_keys('your_password')
password_input.submit()
# 等待页面加载完成
driver.implicitly_wait(10)
```
4. 获取token和session
```python
# 获取token
token_element = driver.find_element_by_xpath('//input[@name="token"]')
token = token_element.get_attribute('value')
# 获取session
session = driver.get_cookie('session')['value']
```
注意:获取到的token和session只有在登录状态下才有效,需要在登录成功后立即获取才能保证有效性。同时也需要根据网站的具体实现来定位token和session对应的HTML元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)