在Ubuntu上使用Python Selenium上传文件

时间:2017-10-06 18:12:33

标签: python linux selenium ubuntu-16.04

我编写了一个利用Selenium的Python脚本,自动将原始GPS数据文件上传到OPUS [https://www.ngs.noaa.gov/OPUS/]进行研究。我有一个完美的Windows版本,现在我正在尝试使它在Linux / Ubuntu 16.04计算机上运行。不幸的是,我在尝试将文件上传到OPUS网站时遇到错误。我的代码如下:

import os
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

directory = 'Documents/UNAVCO/HCC1/Y13' # Directory of GPS data files

# Loop through all files within the specified directory
for file in os.listdir(directory):

 driver = webdriver.Chrome() # Open Chrome Driver
 driver.get('https://www.ngs.noaa.gov/OPUS/') # Navigate to OPUS 
 website
 time.sleep(5) # Wait 5 seconds

 full_dir = os.path.join(directory,file)
 print full_dir
 file_upload = driver.find_element_by_name('uploadfile')
 file_upload.send_keys(full_dir)

 ID = 'TRM55970.00' # ID of GPS atenna  
 antenna_type = 
 driver.find_element_by_xpath("//option[contains(text(),'%s')]"%ID)         
 antenna_type.click() # Select the option

 h = driver.find_element_by_name('height') #Find height element from 

 h.clear() # Clear element
 h.send_keys('2.00') # Set value of height element

 email = driver.find_element_by_name('email_address') # Find email 
 element from HTML
 email.send_keys('zacpopus@gmail.com') # Set email element to 
 recipient

 submit = driver.find_element_by_name('Static').click() # Submit 
 current data file
 time.sleep(1)

 os.remove(full_dir) # Delete file
 driver.close() # Close the browser

 print(file + ' ' + 'uploaded') # Visual of files uploaded

我收到以下错误:

enter cTraceback (most recent call last):
File "/home/zacparra/OPUSpush.py", line 24, in <module>
file_upload.send_keys(full_dir)
File "/usr/local/lib/python2.7/dist-
packages/selenium/webdriver/remote/webelement.py", line 352, in 
send_keys
'value': keys_to_typing(value)})
File "/usr/local/lib/python2.7/dist-
packages/selenium/webdriver/remote/webelement.py", line 501, in 
_execute
return self._parent.execute(command, params)
File "/usr/local/lib/python2.7/dist-
packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-
packages/selenium/webdriver/remote/errorhandler.py", line 194, in 
check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: unknown error: path is not absolute: 
Documents/UNAVCO/HCC1/Y13/hcc11750.13d
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.26.436382 
(70eb799287ce4c2208441fc057053a5b07ceabac),platform=Linux 4.10.0-35-
generic x86_64)ode here

如上所述,稍微修改过的代码版本可以在Windows操作系统上完美运行。我已经找到了上传文件的替代方法,但还没有找到解决这个问题的正确方法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

directory变量的值为Documents/UNAVCO/HCC1/Y13,表示相对路径。在python selenium中,您需要提供文件或目录的绝对路径。

因此请将directory变量初始化为绝对路径。这应解决问题。