[英]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.