如何在Watir中设置Cookie?Chrome爬取站点遇Cookie设置报错求助
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
domainparameter incookies.addmatches 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
gotoURL 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

