硒:如何在单击按钮后获取页面源代码 [英] selenium: How to get page source code after clicking a button

查看:106
本文介绍了硒:如何在单击按钮后获取页面源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将硒与python一起使用来测试我的网络服务器.我需要的是在输入文本中填充文本,然后单击一个按钮以将消息提交到我的服务器并打开一个新的网页.

I'm using selenium with python to test my web server. What I need is to fill text in an input-text and click a button to submit messages to my server and open a new web page.

这是我的代码:

Here is my code:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("http://www.example.com")
txt = driver.find_element_by_id('input-text')
txt.clear()
txt.send_keys('some messages')
btn = driver.find_element_by_id('input-search')
btn.click()
# How to print the source code of the new page here?
# I think it should be as below but I don't know how to do it:
# driver.get("new link")   <---- How to get the new link?
# print(driver.page_source.encode('utf-8'))

当我执行上面的python代码时,一切正常:

When I execute the python code above, everything works fine:

www.example.com打开.
some messages填充在 输入文本.
单击输入搜索按钮.
新网站 页面已打开.

www.example.com is opened.
The some messages are filled in the input-text.
The button input-search is clicked.
The new web page is opened.

现在我需要打印新网页的页面源代码,可以通过单击按钮打开它,但是我不知道该怎么做.

Now I need to print the page source code of the new web page, which is opened by clicking the button, but I don't know how to do this.

print(driver.page_source.encode('utf-8'))只是给我www.example.com的源代码,而不是新的网页.

print(driver.page_source.encode('utf-8')) just gives me the source code of www.example.com, instead of the new web page.

推荐答案

如果将新页面加载到新的选项卡或窗口中,则需要先将硒的上下文更改为该新窗口:

If the new page is loaded in a new tab or window, you will need to change the context of selenium to this new window first:

driver.switch_to_window(driver.window_handles[1])

下一步是等待新内容加载完毕,然后可以使用以下代码获取代码:

The next step is to wait until the new content is loaded and then you can get the code with:

print(driver.page_source.encode('utf-8'))

这篇关于硒:如何在单击按钮后获取页面源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆