【问题标题】:Java HTML (twitter) parsingJava HTML (twitter) 解析
【发布时间】:2016-05-08 11:27:19
【问题描述】:

我正在解析一个内容通常是一些推文的网站,所以我只想获取推文,我检查了网站结构,我想从中获取信息的代码如下所示:

<div class="tweet">
    <a href="https://twitter.com/Sweden" target="_blank" class="tweet__link">@sweden</a>
    <span class="tweet__timestamp"><a href="https://twitter.com/sweden/status/691294898453110784" target="_blank" class="tweet__permalink">Jan. 24, 2016, 5:22 p.m.</a></span>
    <p class="tweet__content">None of them should count when it comes to how you get treated by authorities. <a href="https://t.co/NdSZd3YBTk" rel="nofollow">https://t.co/NdSZd3YBTk</a></p>
</div>

我想得到里面的所有东西 我尝试了以下代码,但没有成功。

public static void main(String[]args) throws IOException {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://curatorsofsweden.com/curator/aleksandra-boscanin/");

        By tweetSelector = By.cssSelector("div[class='tweet'] a");

        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.presenceOfElementLocated(tweetSelector));

        List<WebElement> tweetElements = driver.findElements(tweetSelector);
        for (WebElement tweetElement : linkElements) {
            String tweet= tweetElement.getAttribute("p class");

                System.out.println("Tweet" + tweet);


        }
        driver.quit();
        }

【问题讨论】:

  • 您遇到了什么错误,您到底想在控制台中打印什么?

标签: java html parsing selenium twitter


【解决方案1】:

您的cssSelectorgetAttribute 错误。要通过 cssSelector 查找子项,您需要使用 &gt; By.cssSelector("div[class='tweet'] &gt; a");,而 getAttribute 不获取标签作为参数,仅获取“class”、“id”、“href”等属性。

试试

List<WebElement> tweets = driver.findElements(By.className("tweet")); //find all the <div> tags

for (WebElement tweet : tweets) {
    List<WebElement> tweetContent = tweet.findElements(By.xpath("*")); //find all intimidate children of the <div>

    String href = tweetContent.get(0).getAttribute("href"); //get href of the first <a>
    String timeStamp = tweetContent.get(1).findElement(By.tagName("a")).getText(); //get the content of the <a> in <span>
    String tweet = tweetContent.get(2).findElement(By.tagName("a")).getText(); //get the content of the <a> in <p>

}

这将遍历页面中的所有推文并提取内容。

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 2010-09-19
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多