一、sel = driver.find_elements_by_xpath('//*[@id="nr"]')
# 搜索结果显示条数
二、sel = driver.find_element_by_xpath("//*[@id='nr']"
代码每次运行到1的时候,提示:AttributeError: 'list' object has no attribute 'tag_name',一开始觉得是路径错了,抓不到,换了方式仍是不行。
看了别人例子,觉得是单引号和双引号形成的(知道单双引号效果是同样的,但心理做祟,人家的就是正确,改),就改为和人家例子同样的,仍是报错。
再瞅,发现哪里不同了,想打本身一顿了,发现element多了一个s,就使用2方式,对。
查找缘由,函数解释以下:
def find_element_by_xpath(self, xpath):
"""
Finds an element by xpath.
:Args: - xpath - The xpath locator of the element to find.
:Returns: - WebElement - the element if it was found
:Raises: - NoSuchElementException - if the element wasn't found
:Usage: element = driver.find_element_by_xpath('//div/td[1]')
"""
return self.find_element(by=By.XPATH, value=xpath)
def find_elements_by_xpath(self, xpath):
"""
Finds multiple elements by xpath.
:Args: - xpath - The xpath locator of the elements to be found.
:Returns: - list of WebElement - a list with elements if any was found. An empty list if not
:Usage: elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
"""
return self.find_elements(by=By.XPATH, value=xpath)
find_element()只会查找页面符合条件的第一个节点,并返回;可是定位不到元素则会报错。函数
find_elements()查找多个元素而且返回一个列表,列表里的元素全是WebElement节点对象;当定位不到元素时不会报错,会返回一个空列表。spa