WebDriver按类名称查找

时间:2018-12-07 14:04:21

标签: python selenium class css-selectors webdriverwait

我正在尝试使用class属性和硒WeDriver在网页上查找信息。我希望在以下HTML中打印出 6 + 8

<a href="/#/basic-math-pre-algebra/16869" class="question-link"><b>6 + 8</b> = </a>

我正在按类名搜索,并且我也尝试过XPATH。 XPATH是:

//*[@id="question-link"]

我的代码:

from selenium import webdriver

url_rice = 'http://freerice.com/#/basic-math-pre-algebra/16869'

driver = webdriver.Chrome()
driver.get('http://freerice.com/#/basic-math-pre-algebra/16869')

def question():
    print(driver.find_elements_by_class_name("question-link"))

question()

driver.quit()

1 个答案:

答案 0 :(得分:2)

根据您的问题,您不能仅将测试限制为课程 属性。有时 CSS-SELECTOR 会表现得更好,而有时 XPATH 会派上用场。

根据HTML DOM,文本 6 + 8 位于祖先节点中,且 class 属性为问题链接,其中一个 descendent节点<b>,实际上包含所需的文本。因此,使用 CSS-SELECTOR XPATH ,您需要标识<b>节点。

要提取信息,您需要诱使 WebDriverWait 使所需的元素可见,并且可以使用以下解决方案:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('http://freerice.com/#/basic-math-pre-algebra/16869')
print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.block-means-vocab div#question-title b"))).text)

注意:按照最佳做法,请始终以最大化模式打开浏览器,并禁用 信息栏扩展

相关问题