gpt4 book ai didi

r - 如何使用 RSelenium 检查网页中是否存在元素?

转载 作者:行者123 更新时间:2023-12-02 04:37:57 24 4
gpt4 key购买 nike

我一直试图从一个网站获取特性列表数据,该网站有时有一个“查看更多”按钮来加载更多结果,但有时却没有。在第一种情况下,我一直在使用下面的代码,它工作正常。例如,

  url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=2&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment,Residential-House,Villa&cityName=Navi-Mumbai&Locality=Vashi"
remDr$navigate(url)
Sys.sleep(3)
webElem <- remDr$findElement("css", "#viewMoreButton a")
while(webElem$isElementDisplayed()[[1]]){
tryCatch({
Sys.sleep(1)
webElem <- remDr$findElement("css", "#viewMoreButton a")
webElem$clickElement()
}, error=function(e){})
}
mb<- read_html(remDr$getPageSource()[[1]])

但在第二种情况下,它不起作用。例如:

  url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=4&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment,Residential-House,Villa&cityName=Navi-Mumbai&Locality=Vashi"
remDr$navigate(url)
Sys.sleep(3)
webElem <- remDr$findElement("css", "#viewMoreButton a")
while(webElem$isElementDisplayed()[[1]]){
tryCatch({
Sys.sleep(1)
webElem <- remDr$findElement("css", "#viewMoreButton a")
webElem$clickElement()
}, error=function(e){})
}
mb<- read_html(remDr$getPageSource()[[1]])

此代码卡在“WebElem<- renDr$findElement()”行,不会向前移动或抛出错误。

我做错了什么?

最佳答案

添加 if 条件解决问题:

  url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=4&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment,Residential-House,Villa&cityName=Navi-Mumbai&Locality=Vashi"
remDr$navigate(url)
Sys.sleep(3)
if(length(remDr$findElements("css", "#viewMoreButton a"))!=0){
while(webElem$isElementDisplayed()[[1]]){
tryCatch({
Sys.sleep(1)
webElem <- remDr$findElement("css", "#viewMoreButton a")
webElem$clickElement()
}, error=function(e){})
}
}
mb<- read_html(remDr$getPageSource()[[1]])

关于r - 如何使用 RSelenium 检查网页中是否存在元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40366291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com