简体   繁体   中英

Python Selenium return HTML location

I have a simple HTML table consisting only of tr/td. I need to return exact table row , table column number of an exact record. Solution should be able to handle any number of rows/columns. To find that item I use:

webdriver.find_element_by_xpath("//*[contains(text(), '8')]")

Now I need to return it's location, so far I've been looking into attributes like value_of_css_property / getCssValue etc. I'm new to selenium, any help would be appreciated.

If you need to locate a row containing a td element containing a specific text:

element = webdriver.find_element_by_xpath("//tr[contains(td, '8')]")

Or, if you need to locate a specific cell ( td element):

element = webdriver.find_element_by_xpath("//td[contains(., '8')]")

Then, you can get the location :

print(element.location)

This would give you the coordinates of the element on the page.


If you need to get the row and column number of a cell containing the desired text:

table = webdriver.find_element_by_id("mytable")

rows = table.find_elements_by_tag_name("tr")
for row_index, row in enumerate(rows, start=1): 
    cells = row.find_elements_by_tag_name("td")

    for column_index, cell in enumerate(cells, start=1):
        if "8" in cell.text:
            print("Found a match!")
            print(row_index, column_index)
            break

You can get the location in height or width of the page using the following

WebElement needed = webdriver.find_element_by_xpath("//*[contains(text(), '8')]"); //this puts it in a callable element for you
needed.getLocation().getY(); //this will give the height on the page
needed.getLocation().getX(); //this will give the width on the page

But really you're not actually getting the xpath. What you'd be better doing is to find the table you're looking to traverse and do something along these lines.

List<WebElement> tableRows = webDriver.findElements(By.xpath("tbody[1]/tr"))
    for (WebElement singleRow: tableRows)/*gets the table rows in a List*/
    {
        List<WebElement> cells = singleRow.findElements(By.xpath("td"))
        for (WebElement singleCell: cells)/*gets the rows cells in a List*/
        {
             trIteratorForRowCount++
             if (singleCell.getText().contains('8'))
             {
                  tdIteratorForCellCount++
                  print (("Total cell is (%s, %s) " % (trIteratorForCellCount, tdIteratorForCellCount))
             }
        }
    }

I know this task, here is your solution

class ElementNotFoundInTable(Exception):
    pass


def find_number(table_content, number):
    """
    returns position of element in the table,
    indexes start from 0

    :param table_content: a content of tbody element
    :param str number: a number to look for in the table
    :return:
    """
    table_content = table_content.strip("<trd/>")
    table_rows = table_content.split("</td></tr><tr><td>")
    for table_row in table_rows:
        if number in table_row:
            row_idx = table_rows.index(table_row)
            column_idx = table_row.split("</td><td>").index(number)
            return row_idx, column_idx
    raise ElementNotFoundInTable("Element '{0}' is not found in the table".format(number))



tbody = self.driver.find_element_by_css_selector("table tbody")
tbody_src = tbody.get_attribute("innerHTML")
find_number(tbody_src, '8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM