温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to update an xpath dynamically based on the value from workbook using python/selenium

其他 - 如何使用python / selenium根据工作簿中的值动态更新xpath

发布于 2020-03-27 10:49:26

我必须根据excel工作表中给出的年份来选择任何年份,因为现在我已经直接在代码中给出了这一年。能够直接从excel工作表中获取城市的数据,并且对该年份进行硬编码也可以。有n年的链接(而不是下拉列表),而不是每年写xpath,有没有办法从excel工作表中获得给定的值并将其放置在xpath中说“ year”。Yearlink = driver.find_element_by_xpath('// span [contains(text(),“ year”)]''); 我目前正在使用spyder-python 3.7

请找到我尝试过的代码

driver = webdriver.Chrome  
driver.fullscreen_window();
driver.get('url');
time.sleep(5) 
Workbook=xlrd.open_workbook("excel path")
Details = Workbook.sheet_by_index(0);
city=Details .cell(1,0)
Citytextbox=driver.find_element_by_xpath('//input[@id="city"]');
Citytextbox.send_keys(city.value);
Yearlink=driver.find_element_by_xpath('//span[contains(text(),"2000")]');
Yearlink.click();
time.sleep(10)

更新:添加了html的某些部分,如果还有其他方法也请告知我

<span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1910

      </span>

    </li><li _ngcontent-c26="" class="option">

      <span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1911

      </span>

    </li><li _ngcontent-c26="" class="option">

      <span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1912

      </span>

    </li><li _ngcontent-c26="" class="option">

      <span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1913

      </span>

    </li><li _ngcontent-c26="" class="option">

      <span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1914

      </span>

    </li><li _ngcontent-c26="" class="option">

      <span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1915

      </span>

    </li><li _ngcontent-c26="" class="option">

      <span _ngcontent-c26="" class="toggle link" ng-reflect-klass="toggle link" ng-reflect-ng-class="">

        1916

      </span>    

更新 当我尝试下面的方法时,我收到此错误。我从excel传递值1979,如果我不加'则从excel传递'1979,它将其作为数字值。

InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //span[normalize-space(.)='text:'1979''] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//span[normalize-space(.)='text:'1979'']' is not a valid XPath expression. 

Excel图片 Excel屏幕截图

查看更多

查看更多

提问者
saranya
被浏览
57
saranya 2019-07-16 16:32

我能够根据提供的建议找到解决方案。必须为上述解决方案添加“值”才能正常工作

workbook = xlrd.open_workbook("excel path")
sheet = workbook.sheet_by_index(0)
year_from_excel = sheet.cell(1, 1)
year_link = driver.find_element_by_xpath("//span[normalizespace(.)='{}']".format(year_from_excel.Value))
year_link.click()

发布
问题

分享
好友

手机
浏览

扫码手机浏览