How to locate style element in Selenium Python?

牧云@^-^@ 提交于 2021-01-20 11:45:08

问题


Hello I want to locate a style element / style elements with Selenium Python,

<div style="flex-direction: column; padding-bottom: 65px; padding-top: 0px;">

I tried it in ways like:

self.driver.find_elements_by_xpath("//div[@class='flex-direction:column;padding-bottom:835px;padding-top:0px;']/div")

But it does not work. So how do I locate these elements using Selenium Python?


回答1:


The provided HTML has no class attribute. However in your xpath you have provided class attribute it should be style attribute.

//div[@style='flex-direction: column; padding-bottom: 65px; padding-top: 0px;']

Ideally your code should be

self.driver.find_elements_by_xpath("//div[@style='flex-direction: column; padding-bottom: 65px; padding-top: 0px;']")



回答2:


The HTML is of a <div> element which predominantly contains the <style> attribute for it's descendant(s). It would be highly undesirable to locate element/elements based on only the <style> attribute.


Solution

Instead it would be better to move to the descendant and locate the element(s) with respect to their (common) attributes. As an example:

  • Using class_name:

    elements = driver.find_elements(By.CLASS_NAME, "class_name")
    
  • Using id:

    elements = driver.find_elements(By.ID, "id")
    
  • Using name:

    elements = driver.find_elements(By.NAME, "name")
    
  • Using link_text:

    elements = driver.find_elements(By.LINK_TEXT, "link_text")
    
  • Using partial_link_text:

    elements = driver.find_elements(By.PARTIAL_LINK_TEXT, "partial_link_text")
    
  • Using tag_name:

    elements = driver.find_elements(By.TAG_NAME, "tag_name")
    
  • Using css_selector:

    elements = driver.find_elements(By.CSS_SELECTOR, "css_selector")
    
  • Using xpath:

    elements = driver.find_elements(By.XPATH, "xpath")
    


来源:https://stackoverflow.com/questions/65773969/how-to-locate-style-element-in-selenium-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!