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

如何在Watir中设置Cookie?Chrome爬取站点遇Cookie设置报错求助

Fixing "Cookies are disabled inside 'data:' URLs" Error in Watir + Chrome

I’ve run into this exact issue before—here’s what’s happening and how to fix it:

The error pops up because when you initialize Watir’s Chrome browser, it defaults to loading a blank data:text/html;charset=utf-8 page. Browsers block cookie operations on data: URLs for security reasons, so trying to set your location cookie here will fail every time.

The Fix: Switch to the Target Site’s Context First

Cookies are tied to specific domains, so you need to first navigate to any valid page on the target website (even a 404 error page works, as long as it’s under the target domain) before setting your cookie. This moves the browser into the correct domain context where cookie operations are allowed.

Here’s a step-by-step code example:

require 'watir'

# Initialize the browser
browser = Watir::Browser.new :chrome

# First, navigate to a page on your target domain (e.g., the homepage or a dummy path)
# Even if this page loads a 404, it will establish the domain context
browser.goto 'https://your-target-site.com/'

# Now set your location cookie—this will work because we're in the target domain's context
browser.cookies.add('location_param', 'your-location-value', domain: 'your-target-site.com')

# Finally, navigate to the page you need to scrape
browser.goto 'https://your-target-site.com/desired-page'

# Proceed with your scraping logic...

Key Notes:

  • Make sure the domain parameter in cookies.add matches the target site’s domain exactly (no extra slashes or paths).
  • If the target site redirects you to a login page or another subdomain, adjust the goto URL and cookie domain accordingly.
  • Avoid trying to set cookies immediately after browser initialization—always anchor to the target domain first.

内容的提问来源于stack exchange,提问作者Amrit Pal Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:06:49