Trying to select link text within a table cell if

2019-07-26 00:21发布

问题:

So I have a table cell that contains both text and a link. Now every row in this table has the same text link hyperlink title "[Details]" but the location changes on where it takes you based on which row you are in.

For example the cell will look like this: "Text I Want" [Details]

I want to be able to go to the correct link based on what text is also within that cell, but am having some issues figuring out how to code that in Python. Once a row in this table is clicked it moves it location in the table so using Xpath is out.

Here is what I've tried:


MyText = driver.find_element_by_xpath("//span[text()='My Desired Text']")
MyText.find_element_by_partial_link_text("Details").click()



def click_me(myString):
    WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//td/span[.='" + myString + "']//following::span[2]"))).click()

click_me("My Desired Text")

But I think I'll need to use if statements to actually get the desired results. Any suggestions would be appreciated.


<td>
                            <span>My Desired Text</span>
                            <span class="HSpacer10"></span>
                            <span class="commonLink" onclick="handleMyEvents(EVENT_EDIT_PKG, 60000,1);">[Details]</span>


                        </td>

回答1:

As the table is consisted of multiple texts and associated links with same text as Details you can write a method as follows:

def click_me(myString):
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td/span[.='" + myString + "']//following::span[2]"))).click()

Now you can call this method with any of the desired texts to click on the associated link:

click_me("My Desired Text")
# or
click_me("My Text")
# or
click_me("Text")