请给我一段代码,使用python实现以下功能,请尽可能详细地描述每一步骤。现有一个登录需要用户名密码验证码的网站,网站上可以搜索到一些基础数据。我目前有一组用户名密码,我想要使用python模拟接口自动请求(不手动输入验证码)获取cookie,使用cookie请求,获取这些基础数据并将他们输出到excel中。

pdrw1年前 ⋅ 1102 阅读
以下是一段实现上述功能的Python代码:

```python
import requests
import re
import json
import openpyxl
    
# 登录请求函数
def login(username, password):
    # 获取验证码图片
    code_url = "http://www.example.com/getCode"
    response = session.get(code_url)
    # 解析验证码图片
    code_pattern = r'base64,(.*)\''
    code_image = re.findall(code_pattern, response.text)[0]
    # 使用验证码识别API识别验证码
    code_api_url = "http://www.example.com/checkCode"
    code_data = {"img": code_image}
    headers = {
        'Content-Type': 'application/json'
    }
    # 发送验证码识别请求
    code_response = requests.post(code_api_url, data=json.dumps(code_data), headers=headers)
    code = code_response.json().get('result')
    # 构造登录请求
    login_url = "http://www.example.com/login"
    login_data = {
        'username': username,
        'password': password,
        'code': code
    }
    # 发送登录请求
    login_response = session.post(login_url, data=login_data)
    # 返回登录响应
    return login_response

# 获取基础数据函数
def get_data():
    # 构造获取数据请求
    data_url = "http://www.example.com/getData"
    data_response = session.get(data_url)
    # 解析数据并返回
    return data_response.json()

# 将数据存储到excel中
def save_to_excel(data):
    # 创建新的excel工作簿
    wb = openpyxl.Workbook()
    # 获取默认的工作表
    sheet = wb.active
    # 循环保存数据到工作表中
    for row_num, row_data in enumerate(data, start=1):
        for col_num, col_data in enumerate(row_data, start=1):
            sheet.cell(row=row_num, column=col_num, value=col_data)
    # 保存工作簿到本地excel文件
    wb.save("data.xlsx")

# 使用username和password进行登录
username = "my_username"
password = "my_password"
session = requests.Session()
login_response = login(username, password)

# 判断是否登录成功
if "登录成功" in login_response.text:
    # 登录成功,获取cookie
    cookie = session.cookies.get_dict()
    print("cookie:", cookie)

    # 使用cookie获取数据
    session.headers.update({'cookie': '; '.join([f"{key}={value}" for key, value in cookie.items()])})
    data = get_data()
    print("获取到的数据:", data)

    # 将数据存储到excel中
    save_to_excel(data)

else:
    # 登录失败,打印错误信息
    print("登录失败")
    print("错误信息:", login_response.text)
```

具体步骤如下:

1. 导入必要的Python库

   ```python
   import requests
   import re
   import json
   import openpyxl
   ```

2. 实现登录请求函数

   ```python
   def login(username, password):
       # 获取验证码图片
       code_url = "http://www.example.com/getCode"
       response = session.get(code_url)
       # 解析验证码图片
       code_pattern = r'base64,(.*)\''
       code_image = re.findall(code_pattern, response.text)[0]
       # 使用验证码识别API识别验证码
       code_api_url = "http://www.example.com/checkCode"
       code_data = {"img": code_image}
       headers = {
           'Content-Type': 'application/json'
       }
       # 发送验证码识别请求
       code_response = requests.post(code_api_url, data=json.dumps(code_data), headers=headers)
       code = code_response.json().get('result')
       # 构造登录请求
       login_url = "http://www.example.com/login"
       login_data = {
           'username': username,
           'password': password,
           'code': code
       }
       # 发送登录请求
       login_response = session.post(login_url, data=login_data)
       # 返回登录响应
       return login_response
   ```

   - 使用requests库发送HTTP请求,获取验证码图片,并使用正则表达式解析出base64编码的图片内容。
   - 将图片内容发送至验证码识别API,获取识别结果。
   - 构造登录请求,并发送至网站。
   - 返回登录响应。

3. 实现获取基础数据函数

   ```python
   def get_data():
       # 构造获取数据请求
       data_url = "http://www.example.com/getData"
       data_response = session.get(data_url)
       # 解析数据并返回
       return data_response.json()
   ```

   - 使用requests库发送HTTP请求,获取基础数据。
   - 解析返回的JSON格式数据,并返回。

4. 实现将数据存储到excel中的函数

   ```python
   def save_to_excel(data):
       # 创建新的excel工作簿
       wb = openpyxl.Workbook()
       # 获取默认的工作表
       sheet = wb.active
       # 循环保存数据到工作表中
       for row_num, row_data in enumerate(data, start=1):
           for col_num, col_data in enumerate(row_data, start=1):
               sheet.cell(row=row_num, column=col_num, value=col_data)
       # 保存工作簿到本地excel文件
       wb.save("data.xlsx")
   ```

   - 使用openpyxl库创建新的excel工作簿。
   - 获取默认的工作表。
   - 使用循环将基础数据保存到工作表中。
   - 将工作簿保存到本地excel文件。

5. 使用用户名密码进行登录,获取cookie

   ```python
   # 使用username和password进行登录
   username = "my_username"
   password = "my_password"
   session = requests.Session()
   login_response = login(username, password)

   # 判断是否登录成功
   if "登录成功" in login_response.text:
       # 登录成功,获取cookie
       cookie = session.cookies.get_dict()
       print("cookie:", cookie)
   ```

   - 调用上述实现的登录请求函数进行登录。
   - 判断登录是否成功(登录成功的返回值中应包含“登录成功”字样)。
   - 获取登录成功后的cookie,并打印。

6. 利用cookie获取基础数据

   ```python
   # 使用cookie获取数据
   session.headers.update({'cookie': '; '.join([f"{key}={value}" for key, value in cookie.items()])})
   data = get_data()
   print("获取到的数据:", data)
   ```

   - 根据获取到的cookie更新session对象的header,添加cookie信息。
   - 调用上述实现的获取基础数据函数,获取数据。
   - 打印获取到的数据。

7. 将数据存储到excel中

   ```python
   # 将数据存储到excel中
   save_to_excel(data)
   ```

   - 调用上述实现的将数据存储到excel中的函数,将数据存储到本地excel文件中。

全部评论: 0

    相关推荐