我一直在使用Firefox +硒刮。但是,我決定切換到Phantomjs,因爲它應該更快。使用硒Ghostdriver PhantomJS與Python添加餅乾
我現在有問題在使用Phantomjs + ghostdriver + selenium和python時添加cookie。爲了解決這個問題,我一直在尋找解決方案,但我找不到合適的解決方案。
下面是使用的代碼。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC# available since 2.26.0
driver = webdriver.PhantomJS()
driver.get("http://kswarrants.kasikornsecurities.com/www/Tool/calculator")
driver.add_cookie({'name':'Disc', 'value':'YES','Domain':'kswarrants.kasikornsecurities.com'})
options = driver.find_elements_by_xpath('//select[@id="underling0"]/option')
錯誤信息得到:
selenium.common.exceptions.WebDriverException: Message: {"errorMessage":"Can only set Cookies for the current domain","request":{"headers":{"Accept":"applicatio
n/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"110","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1","User-
Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"sessionId\": \"2eb47d00-fdb0-11e5-af40-4fb0a42a2c0b\", \"cookie\": {\"path\": \"/\",
\"name\": \"Disc\", \"value\": \"YES\"}}","url":"/cookie","urlParsed":{"anchor":"","query":"","file":"cookie","directory":"/","path":"/cookie","relative":"/cook
ie","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/cookie","queryKey":{},"chunks":["cookie"]},"urlOriginal":"
/session/2eb47d00-fdb0-11e5-af40-4fb0a42a2c0b/cookie"}}
主要錯誤是 「只能設置Cookie在當前域」。但是,在添加Cookie之前,我已經瀏覽了該網站。我也注意到請求頭中的主機是本地主機127.0.0.1。這可能是問題的根源。有什麼辦法可以解決這個問題嗎?我如何更改請求頭中的主機?提前致謝。