如何在 Rselenium R 中捕获动态 xpath id

How to catch the dynamic xpath id in Rselenium R

我对一个动态 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

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

提前致谢。

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

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

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

或css:a[href*=sendGaSearch]

我就是这样解决问题的。

  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()

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