【发布时间】:2021-04-16 16:37:37
【问题描述】:
我想在所有动态元素生成后解析一个 HTML 页面(例如 Chrome 中的“检查”按钮)。
我做了一些研究,发现了 Selenium API,但我仍然无法得到我想要的。
在 rorgente 中有以下元素“div”:
<div id="tab-match-history" style="display: none;">
<div id="match-history-preload" class="preload-panel">
<div class="preload">
<span>Loading...</span>
</div>
</div>
<div id="match-history-content"></div>
</div>
如您所见,它包含空的“match-history-content”元素。 这个元素是动态创建的,变成:
<div id="match-history-content">
<div class="color-px-spacer submenu"> </div>
<div class="lines-bookmark">
<ul class="ifmenu">
<li class="divider"/>
<li id="mhistory-1-history" class="li0 selected">
<span>
<a onclick="detail_tab(['match-history', '1-history']);">Set 1</a>
</span>
</li>
<li class="divider"/>
<li id="mhistory-2-history" class="li1">
<span>
<a onclick="detail_tab(['match-history', '2-history']);">Set 2</a>
</span>
</li>
<li class="divider"/>
</ul>
</div>
<!-- . . . -->
<div id="tab-mhistory-1-history" style="display: block;">
<table id="parts" class="parts-first">
<tbody>
<!-- . . . -->
</tbody>
</table>
<div class="spacer-block"/>
</div>
<div id="tab-mhistory-2-history" style="display: block;">
<table id="parts" class="parts-first">
<tbody>
<!-- . . . -->
</tbody>
</table>
<div class="spacer-block"/>
</div>
</div>
我需要分析 2 个元素“tab-mhistory-1-history”和“tab-mhistory-2-history”。
问题是 WebDriver.getPageSource() 方法给了我没有动态生成元素的“match-history-content” div。
<div id="match-history-content"></div>
下面是我使用的Java代码:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main( String[] args ) {
final String URL = "https://www.flashscore.it/partita/GIecNDAM/#cronologia-dell-incontro;1";
System.setProperty("webdriver.chrome.driver","C:\\dev_prog\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(URL);
System.out.println(driver.getPageSource());
System.out.println(driver.findElement(By.id("match-history-content")));
System.out.println(driver.findElement(By.id("mhistory-1-history"))); // This command generates the error: no such element: Unable to locate element: {"method":"css selector","selector":"#mhistory\-1\-history"}
driver.close();
driver.quit();
}
}
提前致谢
【问题讨论】:
-
你会想要使用 webdriverwait 和一个预期的条件:selenium.dev/documentation/en/webdriver/waits
-
非常感谢!!!
标签: java selenium html-parsing