Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Selenium and XPATH to extract all rows from a table

I am using Selenium and XPATH to extract all rows from a table, but can only get the first row.

Here is what I am doing:

from selenium import webdriver

path_to_chromedriver = '/Users/me/Desktop/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = "http://www.psacard.com/smrpriceguide/SetDetail.aspx?SMRSetID=1055"

browser.get(url)
browser.implicitly_wait(10)

SMRtable = browser.find_element_by_xpath('//*[@class="set-detail-table"]/tbody')

for i in SMRtable.find_element_by_xpath('.//tr'):
    print i.get_attribute('innerHTML')

browser.close()

The SMRtable variable has all the rows in it when I convert to string and print. When I try to loop through it, it throw a not iterable error.

I also tried using browser.find_element_by_xpath('//*[@class="set-detail-table"]/tbody/tr'), but this only gives me the first row. I tried adding [position()>0] after /tr, but still got just the first row.

How can I get all of the rows?

like image 740
jdesilvio Avatar asked Jun 06 '15 22:06

jdesilvio


People also ask

How will you get the data from table rows in selenium?

We can get all the values inside a table in Selenium with the help of find_elements method. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned.

How do I find the XPath of a row in a table?

Let's select an element in the web table and find its XPath. For Chrome, right-click and inspect the given element to find its XPath. To find the XPath of a UI element in Firefox, right-click on the desired element, go to “Inspect Element” to open the inspector which will help identify its XPath.


1 Answers

You need find_elements_by_xpath() (watch the "s") instead:

for i in SMRtable.find_elements_by_xpath('.//tr'):
    print i.get_attribute('innerHTML')
like image 142
alecxe Avatar answered Oct 19 '22 23:10

alecxe