首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Selenium WebDriver获取HTTP响应代码

如何使用Selenium WebDriver获取HTTP响应代码
EN

Stack Overflow用户
提问于 2011-06-29 00:13:23
回答 7查看 217.9K关注 0票数 123

我已经用Selenium2/WebDriver编写了测试,并想测试HTTP请求是否返回HTTP 403禁止。

有没有可能用Selenium WebDriver获取HTTP响应状态码?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-06-29 04:38:13

简而言之,不是。使用Selenium WebDriver应用程序接口是不可能的。这已经在项目的issue tracker中讨论过了,而且这个特性不会被添加到API中。

票数 74
EN

Stack Overflow用户

发布于 2018-08-19 23:32:16

对于那些使用Python的人,您可以考虑使用Selenium Wire,这是一个用于检查测试期间浏览器发出的请求的库。

您可以通过driver.requests属性访问请求:

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Go to the Google home page
driver.get('https://www.google.com')

# Access requests via the `requests` attribute
for request in driver.requests:
    if request.response:
        print(
            request.url,
            request.response.status_code,
            request.response.headers['Content-Type']
        )

打印:

https://www.google.com/ 200 text/html; charset=UTF-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png 200 image/png
https://consent.google.com/status?continue=https://www.google.com&pc=s&timestamp=1531511954&gl=GB 204 text/html; charset=utf-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png 200 image/png
https://ssl.gstatic.com/gb/images/i2_2ec824b0.png 200 image/png
https://www.google.com/gen_204?s=webaft&t=aft&atyp=csi&ei=kgRJW7DBONKTlwTK77wQ&rt=wsrt.366,aft.58,prt.58 204 text/html; charset=UTF-8
...

该库使您能够访问标题、状态代码、正文内容,以及修改标题和重写URL的能力。

票数 19
EN

Stack Overflow用户

发布于 2013-09-30 17:57:31

您可以使用BrowserMob代理通过HttpRequestInterceptor捕获请求和响应。下面是一个用Java编写的示例:

// Start the BrowserMob proxy
ProxyServer server = new ProxyServer(9978);
server.start();

server.addResponseInterceptor(new HttpResponseInterceptor()
{
    @Override
    public void process(HttpResponse response, HttpContext context)
        throws HttpException, IOException
    {
        System.out.println(response.getStatusLine());
    }
});

// Get selenium proxy
Proxy proxy = server.seleniumProxy();

// Configure desired capability for using proxy server with WebDriver
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);

// Set up driver
WebDriver driver = new FirefoxDriver(capabilities);

driver.get("http://stackoverflow.com/questions/6509628/webdriver-get-http-response-code");

// Close the browser
driver.quit();
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6509628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档