python-3.x - 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()
我需要能够在 Python 中搜索此 HTML,而不必创建文件。
我尝试了以下方法但没有成功:
- 在调试时,复制从返回的字符串
driver.page_source
,将其粘贴到记事本中并保存为 .html 文件。 - 使用 BeautifulSoup 解析
sourceHtml
变量。 - 执行 Javascript 获取整个 DOM:
getDOM = driver.execute_script('return document.documentElement.outerHTML')
time.sleep(5)
用于在运行之前等待页面完成加载(尽管Webdriverdriver.page_source
在回调之前无论如何都会等待完整响应)。
提前谢谢了。
解决方案
我发现了问题。
if
我声明中的字符串也应该是“用户帐户”而不是“用户帐户”,因此它的评估结果为false
。
当我通过调试模式将变量值保存为 html 文件时,它只是变量实际保存的一小部分。这些调试变量值的限制因开发人员环境(Netbeans、Eclipse、VS Code 等)而异。在 VS Code 中,它似乎是 65,536 字节 (2^16)。
我只留下了下一步,但是如果您确实想更改调试变量大小限制,我认为您可以将“键:值”添加到launch.json
文件中(取决于您正在调试的语言)。这是如何为 PHP 做的。
launch.json
当您“启动”进入调试模式时,该文件会应用设置。该文件中有一个名为“添加配置...”的蓝色按钮。它将列出您可以应用于文件的所有设置。
推荐阅读
- go - Go 的泛型结构
- wordpress - 如何在 wordpress 的特定页面上显示谷歌分析统计图表
- c# - EF Core:嵌套实体外键未更新
- r - 给定一个data.table,对于每列上的每个子组,选择第一个非NA
- javascript - 高级下拉菜单
- java - 您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行使用 near table 的正确语法
- google-apps-script - 在高级日历更新后显示对日历事件的更改
- pine-script - 解决OCHL上执行代码的问题
- javascript - 如何在 Nuxt 中处理 setInterval
- visual-studio - 从 Visual Studio 部署到 Hololens 2 模拟器工作正常,但我无法通过 USB 部署到设备本身