Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - How make System.out.println collect links only with child p tags?

How make System.out.println show only links with /p/ ? I'm trying to write a program that would display all links by hashtag on Instagram. I was able to parse all links with the "a" tag. How can I now select links to a photo where /P/ is available?

        String hashtag = null;

        driver.get("https://www.instagram.com/explore/tags/"+hashtag);


        String link_include= "/p/";
       List<WebElement> all_links = driver.findElements(By.tagName("a"));

             if (all_links.contains(link_include)){
                    //What do I need to write here for the variable to show links only with the /p/ ?can I use the append method? And How ?
                }
            }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To create a list of the <a> tags having a clild <p> tag you can use either of the following Locator Strategies:

  • xpath:

    List<WebElement> all_links = driver.findElements(By.xpath("//a[.//p]"));
    
  • To print the link texts using Java8's stream() and getText():

    System.out.println(driver.findElements(By.xpath("//a[.//p]")).stream().map(element->element.getText()).collect(Collectors.toList()));
    

Ideally you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use either of the following Locator Strategies:

  • xpath:

    List<WebElement> all_links = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//a[.//p]")));
    
  • To print the link texts using Java8's stream() and getAttribute("innerHTML"):

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//a[.//p]"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...