【问题标题】:Different page's source code between selenium and the browser itselfselenium 和浏览器本身的不同页面的源代码
【发布时间】:2015-10-26 21:07:47
【问题描述】:

我正在编写一个工具,他的一项操作应该是分析网页来源。 我正在使用 Selenium for Python 和 Firefox 驱动程序。 当我尝试使用webdriver.page_source 命令获取页面的源代码时,我得到的源代码与我从常规的源代码不同(在浏览器中右键单击-> 页面源代码)。 我使用挂钩到应该向页面添加文本的浏览器(我在常规页面源中看到了该文本,但无法通过 selenium 看到它)

例如:

来自浏览器的源代码:

<html>
  <head></head>
  <body>
    <title>Title</title>
    <h1>Test Page</h1>
    <div>THIS DIV INJECTED TO THE BROWSER</div>
  </body>
</html>

来自 Selenium 的源代码:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head></head>
  <body>
    <title>Title</title>
    <h1>Test Page</h1>
  </body>
</html>

我看到了类似的帖子here,但那里的答案不相关。

请注意,我需要 源代码 本身,而不是渲染的代码(我通过 webdriver.execute_script 获得。

如何获取常规源代码?

【问题讨论】:

  • 不同的如何,究竟是什么?
  • 抱歉,我现在编辑了问题。
  • ...但它仍然没有真正回答我的问题。 minimal reproducible example 是必需的。

标签: python firefox selenium


【解决方案1】:

这里最可能的问题是等待问题 - 在页面未完全加载时获取页面源。解决该问题的最佳选择是添加 explicit wait 以等待特定元素出现/可见:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebdriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "myid")))

print(driver.page_source) 

【讨论】:

  • 我不确定driver.get(&lt;requestedURL&gt;) 发生在哪里
  • @Dan 好吧,这只是代码的相关部分,driver.get() 肯定会先于wait.until()
猜你喜欢
  • 1970-01-01
  • 2014-04-23
  • 2013-10-24
  • 2018-05-17
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 2021-06-18
相关资源
最近更新 更多