python - 无法使用 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上传文件。
解决方案
从您的网址看来,硒未找到该元素
selenium.common.exceptions.NoSuchElementException:
Message: Unable to locate element: [id="html5_1cciqvn90sehe7rachs1c3m03"]
在这种特定情况下,输入字段的 id 是自动生成的,这意味着每个会话都会有所不同。您看到的 id 与您通过 selenium 打开时看到的不同。
在这种特殊情况下,我建议通过 XPath 而不是 id 来定位元素
使用 XPath.//input[type = 'file']
或其他东西,以便 selenium 可以识别元素
推荐阅读
- pandas - 如果满足特定条件,如何更新数据框列下的所有值?
- excel - Excel VBA 用户窗体中的 .width 属性没有影响
- excel - 同一宏在一个 Excel 电子表格中工作,但在另一个电子表格中不工作(曾经工作)
- typo3 - tx_seo:将站点地图划分为多个
- python - Django Admin更改列表隐藏用户的选择选项之一
- mapbox - Mapbox:如何使用 MGL_MATCH 表达式设置图层的填充颜色
- javascript - 使用 Cypress 连接到 SQL DB
- apache-spark - 无法使用 spark-atlas-connector 设置 spark 应用程序
- c++ - 在结构之间复制 char 数据
- python - 即使我能够安装其他库,安装 pyinstaller 时出现 SSL 错误