我已经过了每一个相关的问题,但似乎没有一个问题能提供正确的解决办法。我正在编写一个程序,使用selenium代码从Facebook获取好友列表。为此,我使用for循环向下滚动页面,并使用tagname关键字从其中获取好友名称链接文本。在这样做的同时,我得到了共同的朋友和朋友的数量,也在结果。
我注意到每个朋友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);我不使用tagname("a"),而是使用"id"查找好友名称、链接文本,并在其中使用正则表达式/通配符进行搜索。
例如:IntermediateList = box.findElements(By.id("js_(wild card parameter)"));
任何建议都会有帮助,谢谢!
发布于 2015-09-25 10:45:42
您已经在示例中使用了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_)
https://stackoverflow.com/questions/32779962
复制相似问题