【问题标题】:How to locate style element in Selenium Python?如何在 Selenium Python 中定位样式元素?
【发布时间】:2021-01-18 20:17:52
【问题描述】:
您好,我想用 Selenium Python 定位一个样式元素/样式元素,
<div style="flex-direction: column; padding-bottom: 65px; padding-top: 0px;">
我试过这样的方式:
self.driver.find_elements_by_xpath("//div[@class='flex-direction:column;padding-bottom:835px;padding-top:0px;']/div")
但它不起作用。那么如何使用 Selenium Python 定位这些元素呢?
【问题讨论】:
标签:
python
html
selenium
selenium-webdriver
xpath
【解决方案1】:
提供的 HTML 没有 class 属性。但是在您的xpath 中,您提供了class 属性,它应该是style 属性。
//div[@style='flex-direction: column; padding-bottom: 65px; padding-top: 0px;']
理想情况下你的代码应该是
self.driver.find_elements_by_xpath("//div[@style='flex-direction: column; padding-bottom: 65px; padding-top: 0px;']")
【解决方案2】:
HTML 是一个<div> 元素,主要包含其后代的<style> 属性。仅基于 <style> 属性来定位元素是非常不可取的。
解决方案
相反,最好移动到后代并根据元素的(公共)属性定位元素。举个例子:
-
使用class_name:
elements = driver.find_elements(By.CLASS_NAME, "class_name")
-
使用id:
elements = driver.find_elements(By.ID, "id")
-
使用name:
elements = driver.find_elements(By.NAME, "name")
-
使用link_text:
elements = driver.find_elements(By.LINK_TEXT, "link_text")
-
使用partial_link_text:
elements = driver.find_elements(By.PARTIAL_LINK_TEXT, "partial_link_text")
-
使用tag_name:
elements = driver.find_elements(By.TAG_NAME, "tag_name")
-
使用css_selector:
elements = driver.find_elements(By.CSS_SELECTOR, "css_selector")
-
使用xpath:
elements = driver.find_elements(By.XPATH, "xpath")