我在第一个答案中将代码更改为此基础,tnx很多。 但代码将获得文件未找到错误
但是png文件与python脚本在同一路径上。为什么找不到文件?
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
url = "http://zhcn.109876543210.com/"
driver.get(url)
input_field = driver.find_element_by_css_selector('div#container input[type="file"]')
input_field.send_keys('save.png')
submit_upload_button = driver.find_element_by_css_selector('input#postfiles')
submit_upload_button.click()
wait(driver, 60).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.ok>img')))
print("upload done")
我使用python和selenium来模拟上传图像文件,并从web获取OCR结果。这是一个问题。
这是我的代码。我使用time.sleep(30)
等待ocr完成,这一定是个坏主意。所以我想知道如何知道ocr在这里完成。我想在ocr完成时收到通知,所以我可以在页面中找到链接并从链接下载文件。
图像意味着我应该等待ocr完成。
from selenium import webdriver
from binascii import a2b_base64
from selenium.webdriver.common.keys import Keys
import os
import json
import sys
import time
import re
import keyboard
import time
# adding path to geckodriver to the OS environment variable
os.environ["PATH"] += os.pathsep + os.getcwd()
download_path = "dataset/"
def main():
url = "http://zhcn.109876543210.com/"
driver = webdriver.Firefox()
driver.get(url)
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
driver.find_elements_by_id("selectfiles")[0].click()
filename = '6月12日合同扫描件.jpg'
keyboard.write(filename, delay=0)
time.sleep(3)
keyboard.press_and_release('alt+o')
driver.find_elements_by_id("postfiles")[0].click()
time.sleep(30)
lista = driver.find_elements_by_tag_name("a")
for i in lista:
try:
print(i.get_attribute('href'))
except :
pass
driver.quit()
if __name__ == "__main__":
main()
答案 0 :(得分:1)
文件成功上传后,您可以看到“确定”图标,如下图所示
您可以添加ExplicitWait
以获取图标显示在页面上的时刻,其中包含以下代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
url = "http://zhcn.109876543210.com/"
driver.get(url)
input_field = driver.find_element_by_css_selector('div#container input[type="file"]')
input_field.send_keys(filename)
submit_upload_button = driver.find_element_by_css_selector('input#postfiles')
submit_upload_button.click()
wait(driver, 60).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.ok>img')))
print("upload done")
请注意,您可以通过将文件路径作为字符串发送到<input type="file">
元素来处理文件上传 - 您无需单击文件上传按钮并处理对话框窗口