Extract html source code with selenium xpath

2020-05-03 11:23发布

问题:

I want to extract data from a table that is very long. For every row in the table I want to copy a specific HTML code.

My HTML source code (which I fully want to extract) looks like:

<div class="relative">
                  <div id="stats9526577" class="dark"></div>
                  <img src="/detaljer-1.gif" onmouseover="view_stats(9526577, 14, 13, 4, 7, 10, 8, 6, 3);">
                </div> 

I tried the python code:

data = driver.find_elements_by_xpath('//div[@class="relative"]')

How can I print the above HTML source code in python using xpath?

回答1:

To print the html of the elements matching the xpath, you can use get_attribute() with innerHTML as argument, i.e.:

data = driver.find_elements_by_xpath('//div[@class="relative"]')
for el in data:
    html = el.get_attribute('innerHTML')
    print(html)