[英]Extracting element IDs of required forms in selenium/python
我正在使用 Python 中的 Selenium 抓取此页面 ( https://boards.greenhouse.io/reddit/jobs/4330383 ) 并使用以下方法遍历所有必填字段:
required = driver.find_elements_by_css_selector("[aria-required=true]")
。
问题是我无法查看每个元素的id
。 命令required[0].id
(与driver.find_element_by_id("first_name").id
返回一长串字母数字字符和连字符 - 即使id
是 HTML 中的first_name
。有人可以解释为什么id
正在从first_name
更改为这个字符串?我如何查看我期望的实际id
?
此外,在 HTML 中引用关联的 label 的最简单方法是什么(即本例中的“名字”)? 目标是遍历required
的列表,并能够分辨出这些 forms 中的每一个实际上是在询问用户什么。
在此先感谢,欢迎任何建议或替代方案。 以及。
driver.find_element_by_id("first_name")
返回一个 web 元素 object。
为了获得 web 元素属性值,如href
或id
- get_attribute()
方法应该应用于 web 元素 object。
因此,您需要将代码更改为
driver.find_element_by_id("first_name").get_attribute("id")
这将为您提供该元素的id
属性值
你的代码几乎是好的。 您需要做的就是使用 .get_attribute() 方法来获取您的 ID:
required = driver.find_elements_by_css_selector("[aria-required=true]")
for r in required:
print(r.get_attribute("id"))
我要回答我的第二个问题( “How to reference the element's associated label?” ),因为我刚刚使用find_element_by_xpath()
方法结合前面答案中提到的.get_attribute("id")
解决方案解决了这个问题:
ele_id = driver.find_element_by_id("first_name").get_attribute("id")
label_text = driver.find_element_by_xpath('//label[@for="{}"]'.format(ele_id)).text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.