how to find element in a webpage using Rseleni

2019-08-02 02:13发布

问题:

I have the following tag in a webpage:

<a target="PARENT" href="/bin-din/WebOb/mom.ko/6/wo/asaksdaksjd
/5.1.5.5.33.23.23">View Data Set</a>

How can I lookup this element in Rselenium? For example if my current session is saved in remDr, what should I search for:

webElem <- remDr$findElement(??)

I need to search the element using it's display link (View Data Set) since the href link changes over time. Thanks much for your help

回答1:

Try

library(XML)
fileUrl <- ("http:\\wherever you got your file")
doc <- htmlTreeParse(fileUrl, useInternal=T)
xpathSApply(doc, "//a[@href]", xmlGetAttr, "href")

Demonstration:

fileUrl <- "http://kimkardashianonline.org/"
doc <- htmlTreeParse(fileUrl, useInternal=T)
xpathSApply(doc, "//a[@href]", xmlGetAttr, "href")
[1] "http://kimkardashianonline.org/?page_id=2"                                        
[2] "http://www.kimkardashianonline.org/gallery/"                                      
[3] "http://www.kimkardashianonline.org/icons/"                                        
[4] "http://#"                                                                         
[5] "http://kimkardashianonline.org/?page_id=42"   


回答2:

In the answer by @plafort the [@href] was not needed unless you knew ahead of time what you wanted to set the href attribute value to. So here is a general way forward. This works for this url request. Obviously '_blank' isn't what you'd want.


    library(XML)
    library(RCurl)
    gSite <- getURL("http://www.sitepoint.com/web-foundations/target-html-attribute/") 
    sParse <- htmlParse(gSite)
    xpathSApply(sParse, "//a[@target='_blank']", xmlGetAttr, "href") 


回答3:

You can use : webElem$getElementAttribute("href")



标签: r rselenium