我試圖使用Selenium Webdriver與Python 2.7自動完成一項任務。任務如下: 1.打開「https://www.flipkart.com」。 2.搜索'筆記本電腦'。 3.點擊搜索按鈕。 4.無論搜索查詢的答案是什麼,使用排序按鈕對其進行「按熱門程度」排序。如何通過Selenium Webdriver Python選擇「Sort By」元素
代碼
from selenium import webdriver
url="https://www.flipkart.com"
xpaths={'submitButton' : "//button[@type='submit']",
'searchBox' : "//input[@type='text']"}
driver=webdriver.Chrome()
driver.maxmimize_window()
driver.get(url)
#to search for laptops
driver.find_element_by_xpath(xpaths['searchBox']).clear()
driver.find_element_by_xpath(xpaths['searchBox']).send_keys('laptop')
driver.find_element_by_xpath(xpaths['submitButton']).click()
#to sort them by popularity
driver.find_element_by_xpath("////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click()
最後一條語句拋出一個錯誤:
raise exception_class(message, screen, stacktrace)
InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression ////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '////*[@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]' is not a valid XPath expression.
(Session info: chrome=53.0.2785.143)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64)
鑑於我複製的XPath針對特定元素 「排序 - 人氣」 使用Chrome開發者工具(CTRL + SHIFT + I)。
而且,當我嘗試在開發人員工具的控制檯窗口中搜索該xpath時,它會突出顯示相同的元素。
xpath有什麼問題? 幫助!
'不是有效的XPath表達式' - >嘗試「// * ...」而不是「//// * ...」 – Markus
謝謝! It works – neo