Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all table elements in Python using Selenium

I have a webpage which looks like this:

<table class="data" width="100%" cellpadding="0" cellspacing="0">
    <tbody>
        <tr>
            <th>1</th>
            <th>2</th>
            <th>3 by</th>
        </tr>
        <tr>
            <td width="10%"><a href="foo1">5120432</a></td>
            <td width="70%">INTERESTED_SITE1/</td>
            <td width="20%"><a href="foo2">foo2</a></td>
        </tr>
        <tr class="alt">
            <td width="10%"><a href="foo1">5120431</a></td>
            <td width="70%">INTERESTED_SITE2</td>
            <td width="20%"><a href="foo2">foo2</a></td>
        </tr>
    </tbody>
</table>

I want to put those two sites somewhere (interested_site1 and interested_site2). I tried doing something like this:

chrome = webdriver.Chrome(chrome_path)
chrome.get("fooSite")
time.sleep(.5)

alert = chrome.find_element_by_xpath("/div/table/tbody/tr[2]/td[2]").text
print (alert)

But I can't find the first site. If I can't do this in a for loop, I don't mind getting every link separately. How can I get to that link?

like image 303
cosminp Avatar asked Jun 22 '26 15:06

cosminp


1 Answers

It would be easier to use a CSS query:

driver.find_element_by_css_selector("td:nth-child(2)")
like image 170
Kairat Kempirbaev Avatar answered Jun 25 '26 04:06

Kairat Kempirbaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!