我无法找到与HREF链接有元素的定位代码(在失败者标签月环 - 检查附加的图像)。获得NoSuchElementFound例外。使用JavaScript执行和等待已经尝试过。
HTML:
<div style="width:50%;font-size:14px;float:right;">
<h2 class="f16 bold">Losers</h2>
<div class="tabs">
<a href="//money.rediff.com/losers/bse/daily">Daily</a>
</div>
<div class="tabs">
<a href="//money.rediff.com/losers/bse/weekly">Weekly</a>
</div>
<div class="tabs">
<a href="//money.rediff.com/losers/bse/monthly">Monthly</a>
</div>
</div>
对于<a href="foo">
简单的XPath例子
"//a[contains(@href,'foo')]"
硒对这种情况下的最佳实践,是使用LINKTEXT(org.openqa.selenium.By.linkText),它传递的文本标签内,并且将返回平等匹配。为了正确使用,可以使用链也,这里是一个简单的例子:
import org.openqa.selenium.support.pagefactory.ByChained;
import org.openqa.selenium.By;
import static org.openqa.selenium.By.linkText;
import static org.openqa.selenium.By.cssSelector;
public static By chain(final By... bys) {
return new ByChained(bys);
}
public void yourClickMethodOnAElements(final String name) {
click(chain(cssSelector("div.tabs > a"), linkText(name)));
}
public WebElement click(final By by) {
return click(driver.findElement(by));
}
public WebElement click(WebElement element) {
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();
sleepIfNeeded();
return element;
}
这是一个简化版本,你可以用服务员的检查等等等等改进
你可以尝试寻找使用XPath的组件。试试下面的代码。这可以帮助你
driver.findElement(By.xpath("//div[contains(@id,'leftcontainer')]/div[3]/div[3]/a"));
到click()
在元件失败者 - >每月作为所需的元素是一个<iframe>
内所以得:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("https://money.rediff.com/losers/bse/monthly")
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='logwatch']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h2[contains(., 'Losers')]//following::div[@class='curLink tabs']/a[contains(., 'Monthly')]"))).click()