现在我正在开发一个程序,该程序接受用户输入的问题和答案,将它们分成单独的 q 和 a 列表,然后根据问题或答案自动回答问题。由于使用“机器人”的地方是在线的,我使用的是 Selenium Web 驱动程序,这在尝试读取 aria 标签时给我带来了一些问题。我不知道我做错了什么,因为我对 selenium、HTML 或 CSS 一点也不了解。我试图找到每个容器的 aria-label 值,但不知道它是什么
我试图获取文本值的 HTML 示例:
<div class="MatchModeQuestionGridBoard-tile"><div class="MatchModeQuestionGridTile" touch-action="auto"><div class="MatchModeQuestionGridTile-content"><div aria-label="to cloak; to conceal the truth; to offer lame excuses" class="FormattedText notranslate TermText MatchModeQuestionGridTile-text lang-en" style="font-size: 14px;"><div style="display: block;">to cloak; to conceal the truth; to offer lame excuses</div></div></div></div></div>
我的代码片段:
def driver():
driver = webdriver.Chrome()
driver.get(link)
startMatch = driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[2]/button").click()
#find text in matches
container = driver.find_elements_by_class_name('MatchModeQuestionGridTile-content')
containerFile = open("QuizletTerms.txt", "w+")
for _ in list(container):
arialabel = driver.find_elements_by_css_selector("div[aria-label='']")
containerFile.write("\n")
containerFile.write(str(arialabel))
print(arialabel)
containerFile.close()
print("done")
sleep(5)
Output:
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
文本例如披风;隐瞒真相;提供蹩脚的借口存在于孩子身上<div>
以及它的父级<div>
。所以提取它你需要诱导WebDriver等待 for visibility_of_all_elements_located()
您可以使用以下任一方法定位策略:
-
Using CSS_SELECTOR
and get_attribute()
:
print([my_elem.get_attribute("aria-label") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.MatchModeQuestionGridTile-content>div[aria-label]")))])
-
Using XPATH
and get_attribute()
:
print([my_elem.get_attribute("aria-label") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='MatchModeQuestionGridTile-content']/div[@aria-label]")))])
-
Note:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)