使用selenium.webdriver操作无头模式--haedless浏览器上传文件
第一种情况
Selenium 官方文档的方法:文件上传 | Selenium
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(10)
driver.get("https://the-internet.herokuapp.com/upload");
driver.find_element(By.ID,"file-upload").send_keys("selenium-snapshot.jpg")
driver.find_element(By.ID,"file-submit").submit()
if(driver.page_source.find("File Uploaded!")):
print("file upload success")
else:
print("file upload not successful")
driver.quit()
这种方法对于input格式的文件上传格式适用,只要定位到file-upload的input框,然后 send_keys 输入文件路径,click上传即可。
第二种情况:
对点击上传后弹出windows窗口的文件上传,如果是在wiindow上运行的程序可采用autoit或者robot的方法,但是想在linux上采用无头浏览器上传文件显然不行,因为没有UI界面

先说结论,目前没有直接的方法,转换思路
我采用的是先登录系统,然后拿到token后,使用curl 带token参数上传文件,在linux上非常好用,前提是需要利用浏览器F12找到文件上传的接口。
代码如下:
def upload_log(file_path):
'''上传日志文件到 Reportportal'''
# 模拟superadmin用户登录,获取token
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless') # 采用无头模式
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('/usr/bin/chromedriver', chrome_options=chrome_options)
driver.get('http://10.8.8.9:8080/ui/#login')
driver.find_element_by_name('login').send_keys('admin')
driver.find_element_by_name('password').send_keys('admin')
driver.find_element_by_xpath('//button[contains(text(), "Login")]').click()
time.sleep(5)
token = driver.execute_script('return localStorage.getItem("token");')
token_type = token[0]['type']
token_value = token[1]['value']
# 上传文件
Rpurl = "http://10.8.8.9:8080/api/v1/superadmin_personal/launch/import"
command = 'curl -H "Accept: application/json" -H "Authorization: %s %s" -F "file=@%s" -X POST "%s"' % (token_type, token_value, file_path, Rpurl)
p = os.popen(command).readlines()
print(p)
if 'successfully imported' in p[0]:
print('日志已上传网站')
else:
print('日志上传失败')
driver.close()

浙公网安备 33010602011771号