乐闻世界logo
搜索文章和话题

Does PhantomJS support cookies?

1个答案

1

PhantomJS supports cookies. PhantomJS is a headless browser that enables you to interact with web pages using its JavaScript API, including cookie support. You can read, set, and delete cookies via PhantomJS's API.

For example, if you want to set a cookie in a script running with PhantomJS, you can use the following code:

javascript
var page = require('webpage').create(); page.open('http://example.com', function(status) { if (status === "success") { // Set Cookie page.addCookie({ // Corrected from phantom.addCookie to page.addCookie 'name': 'TestCookie', 'value': '123456', 'domain': 'example.com' }); // Reload the page to verify cookie setting page.open('http://example.com', function(status) { var cookies = page.cookies; console.log('Listing cookies:'); for(var i in cookies) { console.log(cookies[i].name + '=' + cookies[i].value); } phantom.exit(); }); } });

The above code first opens a webpage, then adds a cookie named 'TestCookie' with the value '123456'. Subsequently, it reloads the webpage and prints all cookies to verify that the new cookie has been correctly set.

PhantomJS's support for cookies enables it to simulate user login states or other cookie-based operations in automation testing, network monitoring, or web crawling projects.

2024年8月12日 13:54 回复

你的答案