Python Splinter Click Link in Table Conditional

2019-07-29 04:13发布

问题:

Given this (the "sleep" method is so you can see what I'm looking at):

from splinter import Browser
import time
#from selenium.webdriver.support.ui import WebDriverWait
#from selenium.webdriver.remote.webdriver import WebDriver

with Browser() as browser:
    # Visit URL
    url = "https://mdoe.state.mi.us/moecs/PublicCredentialSearch.aspx"
    browser.visit(url)
    browser.fill('ctl00$ContentPlaceHolder1$txtCredentialNumber', 'IF0000000262422')

    # Find and click the 'search' button
    button = browser.find_by_name('ctl00$ContentPlaceHolder1$btnSearch')
    # Interact with elements
    button.first.click()
    #implicitly_wait(time_to_wait=5)
    time.sleep(30)

I want Splinter/Selenium to click on the link in the right column corresponding to the value "Professional Teaching Certification Renewal" in the column to the left (of the same row).

Here's what I've tried so far (after the code above):

tables=browser.find_by_tag('table') #Get all tables
rows=tables.find_by_tag('tr') #Get all rows in the tables
data=rows.find_by_tag('td') #Get the data(cell)s in the rows

My strategy is to locate the row with the value (data) "Professional Teaching Certification Renewal" and, for that corresponding row, click on the link in the right column. I'm not sure if there is a better strategy, but I'm certainly not married to this one if there is.

I cannot figure out (after reading the docs, of course, unless I missed something) how to examine the data object and determine what it contains. If I can do this, I might be able to figure out the rest.

Thanks in advance!

回答1:

Since, from what I understand, you know the Professional Teaching Certificate Renewal text beforehand and can use it to locate the link in the next column, we can first locate the td by text and then proceed to the next sibling td element grabbing the inner link:

certificate_link = browser.find_by_xpath("//td[. = 'Professional Teaching Certificate Renewal']/following-sibling::td/a") 
certificate_link.first.click()