Manoj Kengudelu
Manoj Kengudelu

Reputation: 665

CSS locator: unable to locate element via code

Here is the links I am working on :

https://www.formula1.com/en/results.html/2017/drivers.html

Im trying to retrieve all the names under Driver column.

Following is the css selector Im using in code

dname = name.find_element_by_css_selector('span.hide-for-mobile').text

Testing the code in css selector plugins.See the screenshot enter image description here

Below is the code:

from selenium import webdriver
import os
import csv

chromeDriver = "/home/manoj/workspace2/RedTools/test/chromedriver"
os.environ["webdriver.chrome.driver"] = chromeDriver
driver = webdriver.Chrome(chromeDriver)
driver.get("https://www.formula1.com/en/results.html/2017/drivers.html")

driverNames = driver.find_elements_by_xpath("//th[contains(.,'Driver')]")

for name in driverNames:
    dname = name.find_element_by_css_selector('span.hide-for-mobile').text
    print(dname)
    print('its done')

The Error Im getting at this moment is:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"span.hide-for-mobile"}

What is that im doing incorrect. Help here would greatly appreciated.

Upvotes: 3

Views: 3468

Answers (2)

xyz
xyz

Reputation: 326

driver.get("https://www.formula1.com/en/results.html/2017/drivers.html");
Thread.sleep(200);
for(int i=1;i<=driver.findElements(By.xpath("//tr/td[3]")).size();i++)
{     System.out.println(driver.findElement(By.xpath("html/body/div[2]/main/article/div /div[2]/div[2]/div[2]/div/table/tbody/tr["+i+"]/td[3]")).getText());
}

I tried this in java, you can convert it into python as your knowing

Upvotes: 0

Andersson
Andersson

Reputation: 52665

You're trying to search for span elements that are children of each th in driverNames list... But th has no child elements

You might use

names = [pilot.text for pilot in driver.find_elements_by_css_selector('span.hide-for-mobile')]

to get list of names

Upvotes: 3

Related Questions