Python 代码报错:DeprecationWarning 和 SyntaxError 解决方案
这段代码出现了两个错误:
-
DeprecationWarning:
options.headless = True已经被弃用,推荐使用options.add_argument('--headless')或options.add_argument('--headless=new')来设置无头模式。 -
SyntaxError: 在读取 cookie 文件时,eval 函数遇到语法错误。这是因为 cookie 文件的内容格式不正确,无法被 Python 解释器正确解析。
解决方法:
-
DeprecationWarning: 将
options.headless = True替换为options.add_argument('--headless')或options.add_argument('--headless=new')。 -
SyntaxError:
- 将 cookie 文件的内容以字典形式保存,例如:
{ "_gid": "GA1.2.521438284.1685852601", "login": "srtzimu", "xfss": "qysa23rf7bfqme45", "_ga": "GA1.1.607076236.1685852601", "overlay": "true", "bcs_cookie_live_stream": "1", "overlay_count": "14", "index_ut": "html5", "_ga_RCR9PNF6FL": "GS1.1.1685955589.9.1.1685958086.0.0.0" }- 使用
json模块解析 cookie 文件,代码如下:
import json with open(cookie_file, 'r') as f: cookies = json.load(f)
代码示例:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import os
import json
username = 'srtzimu'
password = '7018dwdx'
cookie_file = 'cookie.txt'
upload_folder = '/home/115/up'
# 设置无头模式
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# 加载 cookie
driver = webdriver.Chrome(options=options)
driver.get('https://imagetwist.com/')
with open(cookie_file, 'r') as f:
cookies = json.load(f)
for cookie in cookies:
driver.add_cookie(cookie)
# 登录
driver.refresh()
time.sleep(5)
if driver.current_url == 'https://imagetwist.com/':
driver.find_element_by_link_text('Sign In').click()
time.sleep(5)
driver.find_element_by_name('user').send_keys(username)
driver.find_element_by_name('pass').send_keys(password)
driver.find_element_by_name('submit').click()
time.sleep(5)
# 上传图片
driver.get('https://imagetwist.com/upload')
for filename in os.listdir(upload_folder):
if filename.endswith('.jpg') or filename.endswith('.png'):
filepath = os.path.join(upload_folder, filename)
driver.find_element_by_id('file').send_keys(filepath)
time.sleep(5)
driver.find_element_by_id('upload').click()
time.sleep(5)
driver.quit()
通过这些更改,代码应该能够正常运行,并成功读取 cookie 文件,完成登录和上传图片的操作。
原文地址: https://www.cveoy.top/t/topic/osh5 著作权归作者所有。请勿转载和采集!