【问题标题】:How to catch the dynamic xpath id in Rselenium R如何在 Rselenium R 中捕获动态 xpath id
【发布时间】:2020-03-03 10:45:41
【问题描述】:

我对一个动态 xpath 有疑问 我尝试使用不同的方法来解决问题,但我还没有找到好的解决方案。

问题是我必须使用一个 xpath,不幸的是,它是动态的,而且它的长度从来都不相同。

这里是生成点击的html代码部分

   <div class="field">
        <a onclick="sendGaSearch();" class="ui button rounded" style="background- 
 color: #3fa9f5;" id="id1a2" href="javascript:;">

在这种情况下,id 是"id1a2",但如果我刷新页面,代码会有所不同。

我找到了这个解决方案,但并不总是有效,因为id="id1a2" 的长度不同。

我的解决办法是:

  cod_html<-webElem$getPageSource()
  x<-str_match(cod_html, ".^*ui button rounded ([^\\.]*)\\..*")[,2]
  cod_c<-str_sub(x, 42,47)
  cod_c2<-paste0("//*[@id=",'"', cod_c,'"',"]")
  webElem <- remote_driver$findElement(using = "xpath",cod_c2)
  webElem$clickElement()

我从页面中提取的 html 代码部分是这样的:

 "\" style=\"background-color: #3fa9f5;\" id=\"id1a2\"
 href=\"javascript:;\">\n\t\t\t\t\t\t\tSearch\n\t\t\t\t\t\t</a>\n\t\t\t\t\t</div>\n\n\t\t\t\t</form>\n\t\t\t\t\n\t\t\t\t<script

有人可以帮我解决这个问题。

提前谢谢你。

【问题讨论】:

    标签: r xpath rselenium


    【解决方案1】:

    为什么要创建基于动态属性的选择器?

    您应该始终使用不变的属性值,并尽可能使用有意义的文本而不是过于笼统的内容,在这种情况下:

     //a[@onclick='sendGaSearch()']
    

    或css:a[href*=sendGaSearch]

    【讨论】:

    • 感谢您的回答。 webElem
    • 测试页面中的xpath然后确保元素可用或者等待它;你得到什么错误?
    • 错误是:Selenium 消息:无法定位元素://a[@onclick="sendGaSearch()"] 错误:摘要:NoSuchElement 详细信息:使用无法在页面上定位元素给定的搜索参数。类:org.openqa.selenium.NoSuchElementException 更多细节:运行errorDetails方法
    • 请检查并测试选择器,然后查看它是否是选择器问题(因为某些内容无效),或者是否是与页面加载相关的问题,而不是等待元素。还要看看它是否找到了多个元素,如果是,你的元素应该是第一个找到的
    • 还要检查 iframe,如果元素在其内部和 iframe,则需要先切换到 iframe
    【解决方案2】:

    我以这种方式解决了这个问题。

      cod_html<-webElem$getPageSource()
      x<-str_extract (string = cod_html, pattern = ("(?<=;\" id=\").*(?=\" href=\"javascript)"))
      cod_c2<-paste0("#",x)
      webElem <- remote_driver$findElement(using = "css selector",value = cod_c2)
      webElem$clickElement()
    

    这样我就可以捕捉到不同长度的动态值了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多