首页 > 解决方案 > Selenium - 为什么 driver.page_source 的值只有在写入文件时才能正确解析?

问题描述

使用 Python,我想从 reddit.com 获取完整的 HTML 代码来搜索字符串,但是我只能得到一个奇怪的小版本。下面 if 语句中的代码没有运行,但它应该运行,因为我知道该字符串存在于整个页面源中(在浏览器开发工具和“查看页面源”浏览器功能中都可以找到该字符串):

driver = webdriver.Firefox()
driver.get('https://www.reddit.com')
driver.add_cookie({'name':'reddit_session', 'value':'###session cookie value goes here###', 'path':'/', 'domain':'reddit.com'})
driver.refresh() # refresh the page to apply the cookie
source_html = driver.page_source

if 'user account' in source_html:
  print("String found.")

driver.close()

这是sourceHTML复制并粘贴到文件中。它有 65,536 字节长,没有任何意义。

起作用的是将变量内容写入文件:

driver = webdriver.Firefox()
driver.get('https://www.reddit.com')
driver.add_cookie({'name':'reddit_session', 'value':'###session cookie value goes here###', 'path':'/', 'domain':'reddit.com'})
driver.refresh() # refresh the page to apply the cookie
source_html = driver.page_source

with open('page.html', 'w') as myfile:
   myfile.write(source_html)

driver.close()

这是我期望写入文件的 580,000 字节的 HTML。

我需要能够在 Python 中搜索此 HTML,而不必创建文件。

我尝试了以下方法但没有成功:

提前谢谢了。

标签: python-3.xseleniumselenium-webdriverselenium-firefoxdriver

解决方案


我发现了问题。

在调试模式下复制变量的值不会为您提供完整的值。

if我声明中的字符串也应该是“用户帐户”而不是“用户帐户”,因此它的评估结果为false

当我通过调试模式将变量值保存为 html 文件时,它只是变量实际保存的一小部分。这些调试变量值的限制因开发人员环境(Netbeans、Eclipse、VS Code 等)而异。在 VS Code 中,它似乎是 65,536 字节 (2^16)。

我只留下了下一步,但是如果您确实想更改调试变量大小限制,我认为您可以将“键:值”添加到launch.json文件中(取决于您正在调试的语言)。这是如何为 PHP 做的

launch.json当您“启动”进入调试模式时,该文件会应用设置。该文件中有一个名为“添加配置...”的蓝色按钮。它将列出您可以应用于文件的所有设置。


推荐阅读