[Python] selenium find_elements

比較厲害的人,可以使用 xpath 或 cssselector 來完成,功力比較弱的就使用 find_elements 來遊歷每一個項目即可。

官方文件:
https://selenium-python-zh.readthedocs.io/en/latest/locating-elements.html

Example usage:

from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, '//button[text()="Some text"]')
driver.find_elements(By.XPATH, '//button')

These are the attributes available for By class:

ID = "id"XPATH = "xpath"LINK_TEXT = "link text"PARTIAL_LINK_TEXT = "partial link text"NAME = "name"TAG_NAME = "tag name"CLASS_NAME = "class name"CSS_SELECTOR = "css selector"

範例2號:

We’ve already seen how to enter text into a textarea or text field, but what about the other elements? You can “toggle” the state of the drop down, and you can use “setSelected” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:

element = driver.find_element_by_xpath("//select[@name='name']")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
    print("Value is: %s" % option.get_attribute("value"))
    option.click()

相關工具:

CSS and XPath checker:
https://chrome.google.com/webstore/detail/css-and-xpath-checker/aoinfihhckpkkcpholfhmkeplbhddipe


CSS Selector Reference
https://www.w3schools.com/cssref/css_selectors.asp

CSS [attribute=value] Selector
https://www.w3schools.com/cssref/sel_attribute_value.asp

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *