【问题标题】:Extract text from an aria-label selenium webdriver (python)从 aria-label selenium webdriver (python) 中提取文本
【发布时间】:2020-09-17 20:59:05
【问题描述】:

现在我正在开发一个程序,该程序接受用户输入的问题和答案,将它们分成单独的 q 和 a 列表,然后根据问题或答案自动回答问题。由于使用“机器人”的地方是在线的,所以我使用的是 Selenium Web 驱动程序,这在尝试读取 aria-label 时给我带来了一些问题。我不知道我做错了什么,因为我对 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)

输出:


[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver webdriver webdriverwait


    【解决方案1】:

    文本,例如隐身;隐瞒真相;提供蹩脚的借口出现在孩子&lt;div&gt; 以及它的父母&lt;div&gt; 中。所以提取它你需要为visibility_of_all_elements_located()诱导WebDriverWait,你可以使用以下Locator Strategies之一:

    • 使用CSS_SELECTORget_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]")))])
      
    • 使用XPATHget_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]")))])
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2023-01-17
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2021-10-29
      相关资源
      最近更新 更多