学python走过的坑 二

1、sel = driver.find_elements_by_xpath('//*[@id="nr"]')
# 搜索结果显示条数
2、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节点对象;当定位不到元素时不会报错,会返回一个空列表。

猜你喜欢

转载自www.cnblogs.com/z977690557/p/10674812.html