AomineDaici
AomineDaici

Reputation: 763

Selecting element with selenium python

We need to click from 1 to 50 respectively

number elements:

1 - <span class="box" style="z-index:99"></span>
2 - <span class="box" style="z-index:98"></span>
3 - <span class="box" style="z-index:97"></span>
4 - <span class="box" style="z-index:96"></span>
5 - <span class="box" style="z-index:95"></span>
6 - <span class="box" style="z-index:94"></span>
7 - <span class="box" style="z-index:93"></span>
8 - <span class="box" style="z-index:92"></span>
My Code :

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://zzzscore.com/1to50/en/?ts=1585514800920")

time.sleep(2)

element_list = driver.find_element_by_css_selector("[style^=index]")

i = 99
while i > 50:
    element_list[i].click()

I want the code to click numbers from 1 to 50 respectively, You can see the elements of the numbers in the attachment, I want to use the pattern (index 99 in element 1, index 98 in element 2...) between the elements, but I couldn't

Upvotes: 0

Views: 167

Answers (1)

Trapli
Trapli

Reputation: 1597

There are at 3 problems in your code.

  1. find_element_by_css_selector returns a single element, not a list. So you won't be able iterate trough the elements. To select multiple elements use a plural form like: find_elements_by_css_selector
  2. the provided css selector is not valid
  3. it seems that you assume that you'll receive the web elements sorted by z-index which is not the case

I recommend learning Xpath, it superior and more useful than css selectors (you may use it later on when you'll have the chance to parse XMLs). But even Xpath won't sort the elements by attribute values like z-index.

What you could do however:

  1. find out how many elements should be clicked
  2. in a for cycle iterate trough from 1 to the desired max
  3. inside the for cycle fabricate a dynamic xpath via f-string to find your element:
    • a div which contains the number you want to click as text div[text()="{i}"]
    • and the div in question has a span which has a box class span[@class="box"]

So basically elem = driver.find_element_by_xpath(f'//*[text()="{i}"]/span[@class="box"]') should be the key for your task.

Upvotes: 1

Related Questions