用Selenium和Xpath查找元素的問題


0

我有一個對我來說很奇怪的問題,因為我寫的代碼很確定可以正常工作!

Config Details

Chrome version: 80.0.3987.132

ChromeDrivers version: same as Chrome version 80 (80.0.3987.106)

OS: Windows 10

IDE: InteliJ

Programming language: c2020_0

TestURL: a2020_0

我目前正在測試,僅出於學習目的,到目前為止一切正常。通常,單擊菜單元素的基本方法是使用以下代碼:

driver.findElement(By.xpath("//div[@data-box-name='Some Value']/div/ul/li[2]/a")).click();

現在我在此頁面上位於更深的菜單類別: https://allegro.pl/kategoria/komputery ,我想單擊" Drukarki i skanery",如下所示:

driver.findElement(By.xpath("//div[@data-box-name='Categories']/div/section/div[2]/ul/li[3]/a"))

我知道這很好,因為當我右鍵單擊此元素並選擇copy Xpath時,它幾乎為我提供了相同的Xpath。它給了我這個:

//*[@id="opbox-category-tree"]/section/div[2]/ul/li[3]/a

我也嘗試過使用此Xpath,但效果也不佳。我連接了屏幕,因此您可能會看到代碼的樣子。

bug

此條目是否可能太深,必須給我的元素更長的路徑?請任何幫助將不勝感激,我現在對此感到困惑。

0

What's the problem then? Both xPaths seem functional. On the other hand, a good practice is to simplify it as much as possible, so it's readable for you in the future and for other people. The following xPath seems a bit more readable to me:

//div[@id="opbox-category-tree"]//a[text()="Drukarki i skanery"]

You don't need to write every element on the way down as in section/div[2]/ul/li[3]/a. Also, [2], [3] etc. are not a good practice, it might change easily in the future, making your xPath disfunctional.

EDIT based on discussion below:

The real problem is that the test flow is as follows:

Given  as a user I opened page "https://allegro.pl/"
When agreement window appears
Then close agreement window
And  choose department Elektronika
And  choose category Komputery
And choose printer categories and scanners

When choose category Komputery is executed, it opens the category "Komputery" on a new browser tab, so you'd need to switch to that new tab first, and then look for "Drukarki i skanery" menu link.