我迭代 a google form survey并尝试添加一些内容(为了以防万一,我试着让它看起来像一个引用)。但是有些字段是年龄的,不允许像这样超过 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)
最佳答案
尝试在 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 - 您如何使用 Selenium 检查属性是否存在并获取其值(如果存在)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198997/