簡體   English   中英

如何通過Selenium Webdriver Python選擇“排序依據”元素

[英]How can I select the “Sort By” element through Selenium Webdriver Python

我試圖使用帶有Python 2.7的Selenium Webdriver自動化一項任務。該任務如下:1.打開“ https://www.flipkart.com ”。 2.搜索“筆記本電腦”。 3.點擊搜索按鈕。 4.無論搜索查詢的答案是什么,請使用“排序”按鈕將它們“按受歡迎程度”排序。

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)

給定我使用Chrome開發人員工具(ctrl + shift + I)復制了該特定元素“按流行程度排序”的xpath。

而且,當我嘗試在開發人員工具的控制台窗口中搜索該xpath時,它會突出顯示相同的元素。

xpath怎么了? 救命!

就語法錯誤而言,在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()

您可以使用以下代碼。

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()

您也可以嘗試使用此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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM