【问题标题】:Selenium - Why is the value of driver.page_source only parsing correctly when written to a file?Selenium - 为什么 driver.page_source 的值只有在写入文件时才能正确解析?
【发布时间】:2020-07-02 01:14:30
【问题描述】:

使用 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()

Here is sourceHTML copy and pasted into a file. It is 65,536 bytes long and doesn't make sense.

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

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()

And here is the 580,000 bytes of HTML that I am expecting that was written to the file.

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

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

  • 在调试时,复制从driver.page_source 返回的字符串,将其粘贴到记事本中并保存为 .html 文件。
  • 使用 BeautifulSoup 解析 sourceHtml 变量。
  • 执行 Javascript 获取整个 DOM:getDOM = driver.execute_script('return document.documentElement.outerHTML')
  • 使用time.sleep(5) 等待页面完成加载,然后再运行driver.page_source(尽管Webdriver 在回调之前一直等待完整响应)。

非常感谢。

【问题讨论】:

  • Selenium 旨在导航 DOM。为什么不使用 webdriver 调用? (不需要 .page_source...它已经存在于浏览器中...)
  • @pcalkins Reddit 不是我想在其中搜索字符串的唯一网站,因此我无法定位特定元素。我想使用 Requests 库来获取 HTML,但即便如此,我还是从 Reddit 得到了相同的简短响应。
  • 我查看了页面,只找到了用户帐户菜单而不是用户帐户。
  • 如果 source_html 中的“用户帐户”,请使用此选项:

标签: python-3.x selenium selenium-webdriver selenium-firefoxdriver


【解决方案1】:

我发现了问题。

Copying a variable's value in debug mode does not give you the full value.

if 语句中的字符串也应该是“User 帐户”而不是“user 帐户”,因此它的评估结果为 false

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

我不理会下一步,但如果您确实想更改调试变量大小限制,我认为您可以将“键:值”添加到 launch.json 文件中(取决于您使用的语言)调试)。 This is how to do it for PHP

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多