You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Perl的Selenium验证网站返回2XX响应?绕开响应码限制

Got it, since Selenium doesn’t give you direct access to HTTP response codes, here’s a reliable Perl solution tailored for JS-heavy, cookie-dependent sites—no element timeouts required:

Approach

We’ll leverage the browser’s Performance API (supported by all modern browsers) to fetch the response status code of the initial page load. Selenium lets us execute JavaScript to access this data directly, which bypasses the need to rely on element presence/absence to infer errors.

Working Code Example

use Selenium::Chrome;

# Initialize the Chrome driver (swap with Firefox if you prefer)
my $driver = Selenium::Chrome->new;
my $target_url = "https://example.com"; # Replace with your target URL

# Navigate to the target URL
$driver->get($target_url);

# Extract the HTTP response status code via browser Performance API
my $status_code = $driver->execute_script(<<'JS');
// Get navigation-related performance entries
const navEntries = performance.getEntriesByType('navigation');
// Return the response status if we have valid entries
return navEntries.length > 0 ? navEntries[0].responseStatus : null;
JS

# Determine and print the result
if (defined $status_code && $status_code >= 200 && $status_code < 300) {
    print "Looks good\n";
} else {
    print "Error\n";
}

# Clean up the driver session
$driver->quit;

Key Notes

  • Performance API Reliability: The navigation type entry captures the initial page load’s request details, including the responseStatus (your HTTP code). This works even for sites that load content dynamically with JS or set cookies during navigation.
  • SPA Adjustments: If you’re dealing with a single-page app where navigation happens via JS (not full page reloads), you’ll need to target resource type entries instead. For example, filter entries by the specific request URL to get its status code.
  • Browser Compatibility: This works with Chrome, Firefox, Edge, and other modern browsers—just make sure your Selenium driver is up to date.

内容的提问来源于stack exchange,提问作者nck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:47:34