一、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