首页 > 解决方案 > 如何用html文件python selenium替换web-request?

问题描述

我想用 html 文件替换 web-request。链接到文件 html 代码https://pastebin.com/BJbgXtg0

我的代码

from selenium import webdriver

file_path = "Mark.html"
with open(file_path) as html_file:
    driver = webdriver.Chrome()
    html_content = html_file.read()
    print(html_content) # prints full file -- OK
    print("--------------------")
    driver.get("data:text/html;charset=utf-8,{}".format(html_content))
    print(driver.page_source) # prints only part of the file --- PROBLEM
    print("---------------------------")
    edu_raw = driver.find_elements_by_xpath("//div[@id='education']/div/div/div")
    print(edu_raw)

问题是print(driver.page_source)只打印文件的一部分

<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Mark Zuckerberg</title><meta name="referrer" content="origin-when-crossorigin" id="meta_referrer"><style type="text/css" nonce="92Mfjw08">/*<![CDATA[*/.bi .bk .cd{color:</style></head><body></body></html>

如何打印整个文件?

标签: pythonselenium

解决方案


您需要使用以下方法加载文件:

driver.get("file://" + absolutePath)

然后您可以使用检索内容

driver.page_source

另一种方法是直接使用JS替换内容:

driver.execute_script(f"var ele=arguments[0]; ele.innerHTML = '{html_content}';", driver.find_element_by_tag_name('html'))

推荐阅读