我正在使用 R(和 RSelenium)从 ESPN 抓取数据。这不是我第一次使用它,但在这种情况下我遇到了错误,并且无法解决这个问题。
考虑此页面:http://en.espn.co.uk/premiership-2011-12/rugby/match/142562.html
让我们尝试抓取时间线。如果我检查页面,我会得到 css 选择器
#liveLeft
像往常一样,我和
checkForServer()
remDr <- remoteDriver()
remDr$open()
matchId <- "142562"
leagueString <- "premiership"
seasonString <- "2011-12"
url <- paste0("http://en.espn.co.uk/",leagueString,"-",seasonString,"/rugby/match/",matchId,".html")
remDr$navigate(url)
并且页面正确加载。到目前为止,一切都很好。现在,当我尝试使用
获取节点时div<- remDr$findElement(using = 'css selector','#liveLeft')
我回来了
Error: Summary: NoSuchElement
Detail: An element could not be located on the page using the given search parameters.
我很困惑。我也尝试过使用 Xpath,但不起作用。我还尝试获取页面的不同元素,但没有成功。唯一返回一些内容的选择器是
#scrumContent
最佳答案
来自评论。
该元素驻留在 iframe
中,因此无法选择该元素。当在 chrome
的控制台中使用 js
和 document.getElementById('liveLeft')
时,会显示此情况。当在整个页面上时,它将返回 null
,即元素不存在,即使它清晰可见。要解决此问题,只需加载 iframe
即可。
如果您检查页面,您将看到 iframe
的 scr
为 /premiership-2011-12/rugby/current/match/142562.html ?view=scorecard
,来自提供的示例。导航到此页面而不是“完整”页面将允许该元素“可见”,因此可以选择 RSelenium
。
checkForServer()
remDr <- remoteDriver()
remDr$open()
matchId <- "142562"
leagueString <- "premiership"
seasonString <- "2011-12"
url <- paste0("http://en.espn.co.uk/",leagueString,"-",seasonString,"/rugby/current/match/",matchId,".html?view=scorecard")
# Amend url to return iframe
remDr$navigate(url)
div<- remDr$findElement(using = 'css selector','#liveLeft')
更新
如果将 iframe
内容加载到变量中然后遍历它更适用,那么下面的示例将展示这一点。
document.getElementById('liveLeft') # Will return null as iframe has seperate DOM
var doc = document.getElementById('win_old').contentDocument # Loads iframe DOM elements in the variable doc
doc.getElementById('liveLeft') # Will now return the desired element.
关于css - NoSuchElementException 使用 RSelenium 抓取 ESPN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479680/