内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我使用Python bindings来运行Selenium WebDriver。
from selenium import webdriver wd = webdriver.Firefox()
我知道可以通过以下代码来获取 webelement :
elem = wd.find_element_by_css_selector('#my-id')
wd.page_source
但是,是否有“element source”呢?
elem.source # <-- returns the HTML as a string
所以,有什么办法用Python获取SeleniumWebDriver中WebElement的HTML源?
当然,我们可以在SeleniumPython中使用下面的脚本获得所有HTML源代码:
elem = driver.find_element_by_xpath("//*") source_code = elem.get_attribute("outerHTML")
如果要将其保存到文件中,请执行以下代码:
f = open('c:/html_source_code.html', 'w') f.write(source_code.encode('utf-8')) f.close()
我建议保存到文件中,因为源代码非常长。