通过 class 名称查找 WebDriver

WebDriver finding by class name

我正在尝试使用 class 属性和 selenium WeDriver 在网页上查找信息。我希望在以下 HTML:

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

我正在按 class 名称搜索,我也尝试过 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()

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

根据 HTML DOM 文本 6 + 8 在具有 祖先节点 中class 属性作为 question-link 有一个 descendent node 作为 <b>它实际上包含所需的文本。因此,使用 CSS-SELECTORXPATH 您需要识别 <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)

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