将变量传递给xpath selenium,Python

时间:2018-05-22 01:38:49

标签: python selenium xpath

这是我尝试将变量传递到xpath的代码。

Traceback (most recent call last):
  File "/Users/jackboland/Library/Mobile Documents/com~apple~CloudDocs/Python/Selenium/8thDistBriefScraping_FUNCTIONVersion.py", line 27, in <module>
    findcase('2013','100604')
  File "/Users/jackboland/Library/Mobile Documents/com~apple~CloudDocs/Python/Selenium/8thDistBriefScraping_FUNCTIONVersion.py", line 18, in findcase
    select = Select(driver.find_element_by_id('SheetContentPlaceHolder_coaCaseSearch_ddlCaseYear'))
  File "/anaconda2/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 353, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/anaconda2/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 957, in find_element
    'value': value})['value']
  File "/anaconda2/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute
    self.error_handler.check_response(response)
  File "/anaconda2/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"SheetContentPlaceHolder_coaCaseSearch_ddlCaseYear"}
  (Session info: chrome=66.0.3359.181)
  (Driver info: chromedriver=2.38.552518 (183d19265345f54ce39cbb94cf81ba5f15905011),platform=Mac OS X 10.13.4 x86_64)

获取以下错误消息:

//*[@id="SheetContentPlaceHolder_coaCaseSearch_ddlCaseYear"]

我试过引号中的字符串(double和single)我试过用str(变量)插入变量。什么都不做&#39;无法获得允许传入变量的函数。

这是相关的HTML。但是,请注意,当我传入实际数字,一年时,上面的代码完美无缺。它只在尝试传入该数字的变量时失败。

{{1}}

1 个答案:

答案 0 :(得分:0)

我想出来了。有效的代码如下:

year = 2014
yearstr = str(year)
casenum = 100604
casenumstr = str(casenum)
select = Select(driver.find_element_by_id('SheetContentPlaceHolder_coaCaseSearch_ddlCaseYear'))
select.select_by_value(yearstr)
#inserts the case number in that box below the year
driver.find_element_by_id('SheetContentPlaceHolder_coaCaseSearch_txtCaseNum').send_keys(casenumstr)