首页 > 解决方案 > 无法使用 python 和 selenium 在网站中上传文件

问题描述

我想在“ http://pdfcompressor.com/ ”网站上自动压缩文件。我使用 selenium 上传文件但没有这样做。下面是代码

file_path = "/home/gugli/Documents/script_py/Dainik_Jagron/h2.pdf"
browser = webdriver.Firefox()
url = 'http://pdfcompressor.com/'
browser.get(url)

我尝试插入输入标签但出错了

browser.find_element_by_id('html5_1cciqvn90sehe7rachs1c3m03').send_keys(filepath)

这是输入标签的快照

以下是错误:

Traceback (most recent call last):
  File "/home/gugli/Documents/script_py/Dainik_Jagron/uploadfiles.py", line 32, in <module>
    browser.find_element_by_id('html5_1cciqvn90sehe7rachs1c3m03').send_keys("/home/gugli/Documents/script_py/Dainik_Jagron/h2.pdf")
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 330, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 832, in find_element
    'value': value})['value']
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 297, 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)
selenium.common.exceptions.NoSuchElementException:

Message: Unable to locate element: [id="html5_1cciqvn90sehe7rachs1c3m03"]

该文件存储在“ul”标签中。但甚至未能在此标签中上传。这是上传文件前后的dom结构快照

上传文件前

上传文件后

上传的文件存储为“li”元素(图3)。我尝试插入“div id = carousel”容器,但再次尝试失败。我怎么能在这里使用python上传文件。

标签: pythonseleniumselenium-webdriverautomation

解决方案


从您的网址看来,硒未找到该元素

selenium.common.exceptions.NoSuchElementException:

Message: Unable to locate element: [id="html5_1cciqvn90sehe7rachs1c3m03"]

在这种特定情况下,输入字段的 id 是自动生成的,这意味着每个会话都会有所不同。您看到的 id 与您通过 selenium 打开时看到的不同。

在这种特殊情况下,我建议通过 XPath 而不是 id 来定位元素

使用 XPath.//input[type = 'file']或其他东西,以便 selenium 可以识别元素


推荐阅读