我已经解决了所有相关问题,但似乎没有一个提供正确的解决方案。我正在编写一个程序,使用 selenium 代码从 Facebook 获取好友列表。为此,我使用 for
循环向下滚动页面,并使用 tagname
关键字从中获取好友姓名链接文本。这样做的同时,我得到了共同的 friend 和每个 friend 拥有的 friend 数量,也在结果中。
我注意到每个 friend ID 都以 js_X
开头,其中 X 可以是任何值。
我需要知道如何使用任何通配符搜索/正则表达式来搜索并向我获取结果。
下面是我的代码(我知道它的编程很糟糕,但请帮助我):
--打开facebook并到达好友列表页面的代码---
WebElement box = d.findElement(By.xpath(".//*[@id='pagelet_timeline_app_collection_100000641984658:2356318349:2']/ul")); **//This find the first box containing friend list**
List<WebElement> FinalList = box.findElements(By.tagName("a")); **//All Names are fetched and added in Final List**
jse.executeScript("scroll(0, 2500)"); **//Scrolled below to second box**
Thread.sleep(15000L);
box = d.findElement(By.xpath(".//*[@id='pagelet_timeline_app_collection_100000641984658:2356318349:2']/ul[2]"));**//This finds second box and fetches all the friends name from that box**
List<WebElement> IntermediateList; **//Temporarylist created**
for(int i=3,k=7; i<17||k<20; i++){
if(i<17){
box = d.findElement(By.xpath(".//*[@id='pagelet_timeline_app_collection_100000641984658:2356318349:2']/ul["+i+"]"));
if(box.isDisplayed()){
IntermediateList = box.findElements(By.tagName("a"));
FinalList.addAll(IntermediateList);
jse.executeScript("scroll(0, "+k+"000)"); **//This is for increasing scroll everytime as sometimes box is further down**
Thread.sleep(15000L);
k++;
}else{
break;
}
}
FinalList.addAll(IntermediateList);
我想使用“id”
而不是tagname("a")
来查找 friend 姓名链接文本并在其中使用正则表达式/通配符进行搜索.
例如:IntermediateList = box.findElements(By.id("js_(通配符参数)"));
任何建议都会有帮助,提前致谢!!
最佳答案
您已经使用过xpath
在您的示例中,为什么不使用 xpath
找到所需的链接?
XPATH:
IntermediateList = box.findElements(By.xpath("//*[contains(@id,'js_')]"));
(查找 ID
包含 js_
的任何元素)
CSS:
IntermediateList = box.findElements(By.cssSelector("a[id^='js_']"));
(查找 ID 以 <a href...>
开头的链接 js_
)
关于java - 如何在 Java Selenium 中使用通配符条目进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32779962/