繁体   English   中英

您如何使用 Selenium 检查是否存在属性并获取其值(如果存在)?

[英]How do you check the presence of an attribute with Selenium and get its value if it is here?

我迭代了一个谷歌表单调查并尝试放置一些内容(我试图让它看起来像一个引用以防万一)。 但是有些字段是年龄,不允许超过 99 岁,如下所示:

<input type="text" class="quantumWizTextinputPaperinputInput exportInput" jsname="YPqjbf" autocomplete="off" tabindex="0" aria-label="Age" aria-describedby="i.desc.504994172 i.err.504994172" name="entry.128750970" value="" min="18" max="99" required="" dir="auto" data-initial-dir="auto" data-initial-value="10102015" badinput="false" aria-invalid="true">

水图像介绍

所以我在我的代码中添加了一个条件来尝试查看我必须写的元素上是否有“max”属性:

        content_areas = driver.find_elements_by_class_name(
            "quantumWizTextinputSimpleinputInput.exportInput"
        )
        for content_area in content_areas:
            if content_area.get_attribute("max") exists:
                max = content_area.get_attribute("max")
                content_area.send_keys(max)
            else:
                content_area.send_keys("10102015")

但它不起作用:

max:
Traceback (most recent call last):
  File "questions_scraper_michael.py", line 151, in <module>
    result = extract(driver, df, column)
  File "questions_scraper_michael.py", line 70, in extract
    "freebirdFormviewerViewNumberedItemContainer"
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 580, in find_elements_
by_class_name
    return self.find_elements(by=By.CLASS_NAME, value=name)
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 1007, in find_elements

    'value': value})['value'] or []
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\antoi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\errorhandler.py", line 241, in check_respo
nse
    raise exception_class(message, screen, stacktrace, alert_text)
selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: {Alert text :
Message: unexpected alert open: {Alert text : }
  (Session info: chrome=83.0.4103.61)

我认为您的解决方案应该是这样的

  content_areas = driver.find_elements_by_class_name(
            "quantumWizTextinputSimpleinputInput.exportInput"
        )
        for content_area in content_areas:
            if content_area.get_attribute("max") and not content_area.get_attribute("max").isspace():
                max = content_area.get_attribute("max")
            else:
                content_area.send_keys("10102015")

css选择器下方尝试识别该页面上的所有input元素,然后迭代循环。

driver.get('https://docs.google.com/forms/d/e/1FAIpQLSe-ebOztdB6T4ZgtsOYuvbUR5qwSTfI5CnJB1mNLeNflCVX8Q/viewform')
content_areas=driver.find_elements_by_css_selector("input.exportInput")
for content_area in content_areas:
    if content_area.get_attribute("max"):
        max = content_area.get_attribute("max")
        content_area.send_keys(max)
    else:
        content_area.send_keys("10102015")

浏览器快照。

在此处输入图像描述

python 中没有“exists”命令。 你应该删除它。

for content_area in content_areas:
    if content_area.get_attribute("max"):
        max = content_area.get_attribute("max")
    else:
        content_area.send_keys("10102015")

总而言之,您的测试涉及:

  • 检查是否存在max属性。
  • 如果存在此类元素,则检索max属性的值。

理想情况下, max属性指定<input>元素的最大值。 因此,您需要为visibility_of_all_elements_located()诱导WebDriverWait并且您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

     driver.get('https://docs.google.com/forms/d/e/1FAIpQLSe-ebOztdB6T4ZgtsOYuvbUR5qwSTfI5CnJB1mNLeNflCVX8Q/viewform') print([my_elem.get_attribute("max") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "input.quantumWizTextinputPaperinputInput.exportInput[max]")))])
  • 使用XPATH

     driver.get('https://docs.google.com/forms/d/e/1FAIpQLSe-ebOztdB6T4ZgtsOYuvbUR5qwSTfI5CnJB1mNLeNflCVX8Q/viewform') print([my_elem.get_attribute("max") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//input[@class='quantumWizTextinputPaperinputInput exportInput' and @max]")))])
  • 控制台 Output:

     ['99']
  • 注意:您必须添加以下导入:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM