【发布时间】: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