【问题标题】:Python selenium Can't access cookiesPython selenium 无法访问 cookie
【发布时间】:2016-10-20 00:33:19
【问题描述】:

我正在尝试使用 python、selenium 和 phantomjs 访问网页。我使用driver.get 获取页面并登录到页面。它说我应该为此启用cookie。

所以我尝试访问以下 cookie:

self.driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any'])
self.driver.get('https://sellercentral.amazon.in/gp/homepage.html')

cks = self.driver.get_cookies()
for cookie in cks:
    print cookie
    print cookie['name'] + ' - ' + cookie['value']

但我在终端中只能看到一个空列表。但是当我使用 mozilla firefox 访问该页面时,为该域设置了多个 cookie。

如何访问这些 cookie 并为 webdriver 设置它们?

【问题讨论】:

    标签: python selenium cookies selenium-webdriver phantomjs


    【解决方案1】:

    PhantomJS 默认启用 Cookie,所以我认为您的操作没有任何问题。

    我认为问题在于亚马逊不支持用户代理中的“Phantomjs/(..*)”。您是否尝试过使用此代码的其他网站?当你说你用 FireFox 试过时,是通过webdriver.Firefox() 吗?

    您可以尝试自定义用户代理;

    from selenium import webdriver
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = (
        "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"
    )
    driver = webdriver.PhantomJS(desired_capabilities=dcap)
    

    Docs 这个。

    但是您应该尝试通过 webdriver.Firefox() 运行它以查看它是否有效,然后可能会读取 webdriver.Firefox() 用户代理并尝试将您的 webdriver.PhantomJS() 用户代理切换到 Firefox 使用的用户代理。

    【讨论】:

    • 不,我没有使用 webdriver 的 firefox。我使用浏览器 firefox 并在其控制台中检查了 cookie。我如何在亚马逊上使用 phantonjs,因为我的所有脚本都在 phantomjs 中,我更愿意将它用于亚马逊。我可以在使用带有 selenium 的 phantomjs 时更改用户代理吗?
    • @ManishGupta 你应该试试webdriver.Firefox(),如果只是为了证明它是亚马逊在嗅探用户代理时所做的。然后试试我添加到答案中的其余内容。
    • 我在 Windows Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/40.1 上使用了这个用户代理,它可以工作,但在 linux 上却不行。然后我使用了我的 linux 用户代理Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0,它仍然无法正常工作。我需要让它在 linux 中工作,因为我将使用 ubuntu 服务器进行脚本部署。
    • @ManishGupta 你用 Firefox 试过了吗?那么至少你可以确定问题是亚马逊不会向 PhantomJS 提供 cookie?
    • 我现在做了,它抛出了`如何修复 Selenium WebDriverException:浏览器似乎在我们可以连接之前已经退出?'
    猜你喜欢
    • 2021-07-20
    • 2021-09-21
    • 1970-01-01
    • 2016-02-16
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2021-07-24
    相关资源
    最近更新 更多