优化代码:import requests import pyautogui from PIL import Image from pyzbar.pyzbar import decode while True: def decode_qr_code(): # 截取屏幕并保存为图片 screenshot = pyautogui.screenshot() screenshot.save('screenshot.png') # 加载图片并解析二维码 image = Image.open('screenshot.png') decoded = decode(image) # 输出二维码内容 if decoded: return decoded[0].data.decode('utf-8') else: return None # 登录请求的URL url = 'https://bbs.mihoyo.com/apihub/api/user/auth' # 请求头信息 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Referer': 'https://bbs.mihoyo.com/', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json;charset=UTF-8'} # 账号和密码 username = '18110615228'password = 'password' # 构造请求体 data = { 'account': username, 'password': password, 'autoLogin': False } # 获取二维码信息 qr_code = decode_qr_code() if qr_code: #将二维码信息添加到请求体中 data['qrCode'] = qr_code #发送登录请求 response = requests.post(url, json=data, headers=headers) # 判断登录是否成功 if response.status_code == 200: print('登录成功') break else: print('登录失败') else: print('未找到二维码')
时间: 2024-02-14 19:35:26 浏览: 93
可以优化的地方有:
1. 每次循环都定义一个函数 `decode_qr_code()`,可以将其定义在循环外部,避免重复定义。
2. 每次循环都截取屏幕并保存为图片,可以将其放到 `decode_qr_code()` 函数中,避免重复截屏。
3. 每次循环都加载图片并解析二维码,可以将其放到 `decode_qr_code()` 函数中,避免重复解析。
4. 账号和密码可以通过命令行参数或配置文件传入,避免硬编码。
综上,可以将代码优化为:
```python
import argparse
import requests
import pyautogui
from PIL import Image
from pyzbar.pyzbar import decode
def decode_qr_code():
# 截取屏幕并保存为图片
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')
# 加载图片并解析二维码
image = Image.open('screenshot.png')
decoded = decode(image)
# 输出二维码内容
if decoded:
return decoded[0].data.decode('utf-8')
else:
return None
def login(username, password):
# 登录请求的URL
url = 'https://bbs.mihoyo.com/apihub/api/user/auth'
# 请求头信息
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Referer': 'https://bbs.mihoyo.com/',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json;charset=UTF-8'
}
# 构造请求体
data = {
'account': username,
'password': password,
'autoLogin': False
}
# 获取二维码信息
qr_code = decode_qr_code()
if qr_code:
# 将二维码信息添加到请求体中
data['qrCode'] = qr_code
# 发送登录请求
response = requests.post(url, json=data, headers=headers)
# 判断登录是否成功
if response.status_code == 200:
print('登录成功')
return True
else:
print('登录失败')
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='登录米游社论坛')
parser.add_argument('username', help='账号')
parser.add_argument('password', help='密码')
args = parser.parse_args()
login(args.username, args.password)
```
阅读全文