2016-10-17 95 views
0

我试图使用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有什么问题? 帮助!

+0

'不是有效的XPath表达式' - >尝试“// * ...”而不是“//// * ...” – Markus

+0

谢谢! It works – neo

回答

1

至于语法错误去在你的XPath替换//////

driver.find_element_by_xpath("//*@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click()

这将解决你的语法错误,并做必要的工作 虽然在我看来更好的XPATH将 driver.find_element_by_xpath("//li[text()='Popularity']").click()

+0

谢谢! 它的工作原理。 – neo

0

你可以使用下面的代码。

from selenium import webdriver 
import time 
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 
time.sleep(5) 
driver.find_element_by_xpath("//li[text()='Popularity']").click() 
0

你可以试试这个CSS选择太:

#container > div > div:nth-child(2) > div:nth-child(2) > div > div:nth-child(2) > div:nth-child(2) > div > section > ul > li:nth-child(2) 

对我来说,cssSelector比XPath的浏览器兼容性也更好。

相关问题