簡體   English   中英

Python和Selenium - 如何在頁面上找到所有元素ID?

[英]Python & Selenium - how do I find all element IDs on a page?

我知道我可以使用如下方法:

find_elements_by_tag_name()
find_elements_by_id()
find_elements_by_css_selector()
find_elements_by_xpath()

但我想要做的只是獲取頁面中存在的所有元素ID的列表,可能還有它們出現的標記類型。

我怎么能做到這一點?

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://google.com')

ids = driver.find_elements_by_xpath('//*[@id]')
for ii in ids:
    #print ii.tag_name
    print ii.get_attribute('id')    # id name as string

以前不必這樣做,但從邏輯上思考你可以使用XPath來做到這一點(可能是其他方式,XPath是我頭腦中出現的第一件事)。

使用find_elements_by_xpath使用XPath //*[@id] find_elements_by_xpath //*[@id]任何具有某種ID的元素)。

然后,您可以遍歷集合,並使用每個元素的.tag_name屬性來查找它是什么類型的元素,並使用get_attribute("id")方法/函數來獲取該元素的ID。

注意:這可能會很慢。 畢竟,你要求提供大量信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM