YuanL
YuanL

Reputation: 67

Python Selenium getting the nth element of an xpath

I'm trying to get the dates on ebay listings (see green square around date in picture) using selenium and find_element_by_xpath but I am having a hard time. I'm trying to get the dates for each listing. I am using Python and Firefox browser.

I thought I could just do the following:

date_x = (driver.find_element_by_xpath("(//span[@class='s-item__ended-date s-item__endedDate'])[2]").text)

but it doesn't work. Not sure how to grab each date, is there something I am doing wrong or an easier way of doing this; if someone could help advise, would be appreciated.

enter image description here

Upvotes: 0

Views: 502

Answers (1)

Skygear
Skygear

Reputation: 90

Your question was a bit unclear to me, wasn't sure if you wanted a specific date or every date on the page. I will give you a solution for every date. I find that searching by class name is much simpler, and I find it more convenient.

for element in driver.find_elements_by_class_name('s-item__time-end'):
    print(element.text)

I entered eBay and it was a bit different for me, namely, the class of the end date was different so I used that instead, but you can change to the class that is necessitated by your needs. Also, instead of printing you probably want to store it in an array.

dates = []
for element in driver.find_elements_by_class_name('s-item__time-end'):
    dates.append(element.text)

As for the code you submitted, there's a syntax error. It should be:

date_x = driver.find_element_by_xpath("(//span[@class='s-item__ended-date s-item__endedDate'])[2]"), at least as far as I'm concerned. 

Upvotes: 1

Related Questions