简体   繁体   中英

How to get the second block of html code with selenium

My code:

from selenium import webdriver
driver.get('http://www.datiopen.it/it/opendata/Mappa_delle_stazioni_ferroviarie_in_Italia')
element = driver.find_element_by_id("Tabella")
time.sleep(5)
element.click()
time.sleep(5)
a=driver.find_element_by_id('rId_48').get_attribute('innerHTML')
print(a)

My output:

<td role="gridcell" style="" title="" aria-describedby="list_"><a title="Vedi su Google Maps" href="javascript:StatPortalOpenData.ODataUtility.openInStreetView(45.0760003999999,7.5911782);"><img alt="Vedi su Google Maps" height="25" width="25" style="vertical-align:middle" src="/sites/all/modules/spodata/metadata/viewer/multidimensional_viewer/img/streetView.png"></a></td>

<td role="gridcell" style="" class="" title="COLLEGNO" aria-describedby="list_Cccomune_608711150">COLLEGNO</td>

My desired output:

<td role="gridcell" style="" class="" title="COLLEGNO" aria-describedby="list_Cccomune_608711150">COLLEGNO</td><td role="gridcell" style="" class="" title="CITTA' METROPOLITANA DI TORINO" aria-describedby="list_Ccprovincia_1472723626">CITTA' METROPOLITANA DI TORINO</td>

So it is the second block of <td> </td>

Thank you!

It looks like you selected the parent element of the <td> you want. Just use a css selector to get all the td elements inside it:

a=driver.find_elements_by_css_selector('#rId_48 td')

Note the "s" in find_elements... . This returns a list of all the <td> elements. So the one you want should be a[1] .

If you want to target specific row and cell value you can use following CSS selector .

To print the element :

print(driver.find_element_by_css_selector("#rId_48>td:nth-child(2)").get_attribute('outerHTML'))
print(driver.find_element_by_css_selector("#rId_48>td:nth-child(3)").get_attribute('outerHTML'))

OR to print the text of the element

print(driver.find_element_by_css_selector("#rId_48>td:nth-child(2)").text)
print(driver.find_element_by_css_selector("#rId_48>td:nth-child(3)").text)

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