python - 如何用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>
如何打印整个文件?
解决方案
您需要使用以下方法加载文件:
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'))
推荐阅读
- css - 选中时突出显示所选类别/子类别(Woocomerce 类别小部件)
- java - Maven 程序集:读取程序集时出错:带有 ID 的描述符
- c++ - C++ 创建菜单并传递参数
- javascript - 是否可以在应用程序在后台运行时检测传感器数据的变化(react-native)?
- javascript - 生成更复杂的 Hapi-swagger 文档
- python - 使用多处理在类内共享属性
- python - 如何调试`can't pickle _thread.RLock objects`?
- java - 测试时抛出 NoDialectException,运行应用程序时工作正常
- oracle - 执行错误 在预期以下情况之一时遇到符号“IF”
- openmdao - 在 OpenMDAO 中,为什么优化器会尝试设计变量的值远远超出指定范围?