[英]Is there a Selenium wrapper to find element with a given selector type as an input (By.css_selector, By.xpath, By.class ...)?
Following methods are available in Python Selenium WebDriver to find multiple elements. Python Selenium WebDriver 中提供了以下方法来查找多个元素。 These methods will return list of elements.这些方法将返回元素列表。
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector
I need ta wrapper ( a function) on top of those find_elements_by_xxxx in order to find any element given element with a given selector type.我需要在那些 find_elements_by_xxxx 之上使用包装器(一个函数),以便找到具有给定选择器类型的给定元素的任何元素。
Why not just write a function that takes By
as a parameter?为什么不写一个以By
作为参数的函数呢?
def find_elements_by(driver, by, locator):
return driver.find_elemements(by, locator)
Then, you can call it like this:然后,你可以这样称呼它:
xpath_result = find_elements_by(driver, By.XPATH, "//input")
class_result = find_elements_by(driver, By.CLASS_NAME, "className")
css_result = find_elements_by(driver, By.CSS_SELECTOR, "css.selector")
You can change this up to make it static so you are just using driver.find_elements_by(By.CSS_SELECTOR, "css.selector")
您可以将其更改为静态,因此您只需使用driver.find_elements_by(By.CSS_SELECTOR, "css.selector")
Most WebDriver implementations have a method find_element
that takes in a By
value and a selector value, which effectively does what Christine wrote.大多数 WebDriver 实现都有一个find_element
方法,它接受一个By
值和一个选择器值,这有效地完成了 Christine 所写的。
driver = ...
driver.find_element(By.ID, "element_id")
driver.find_element(By.CSS_SELECTOR, "css.selector")
The implementation in python's ChromeDriver looks like: python 的 ChromeDriver 中的实现如下所示:
def find_element(self, by=By.ID, value=None):
"""
Find an element given a By strategy and locator. Prefer the find_element_by_* methods when
possible.
:Usage:
element = driver.find_element(By.ID, 'foo')
:rtype: WebElement
"""
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self.execute(Command.FIND_ELEMENT, {
'using': by,
'value': value})['value']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.