[英]WebDriver finding by class name
我正在尝试使用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()
根据您的问题,您不能只将测试限制为class 属性 。 有时发现CSS-SELECTOR在XPATH有时很方便的地方表现更好。
根据HTML DOM ,文本6 + 8在具有class属性作为问题链接的祖先节点内,该祖先节点的后代节点为<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)
注意:按照最佳做法,请始终以最大化模式打开浏览器并禁用信息 栏和扩展名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.