Webdriver phantomjs 点击后不再跟随链接

1 投票
1 回答
1529 浏览
提问于 2025-04-29 14:30

我用一个简单的webdriver phantomjs脚本来更新preloved.co.uk上的一些广告。这个脚本之前运行得很好,但最近开始出现“点击提交但加载失败”的错误,尤其是在点击登录链接之后。根据这个链接的建议,我把phantomjs更新到了最新的稳定版本1.9.7,按照这里的指南进行操作。然而,现在点击登录似乎也没有反应,页面没有重新加载。

第一步就是要进入登录表单页面。

from selenium import webdriver
br = webdriver.PhantomJS(service_log_path='/path/to/logfile.log')
url = "http://www.preloved.co.uk"
br.get(url)

# Go to login page
login_button = br.find_element_by_xpath('//div[@id="header-status-login"]/a')
login_button.click()

通常情况下(如果你把浏览器那一行换成br = webdriver.Firefox()之类的),这会导致页面重新加载到登录页面,脚本会继续执行。但是现在点击似乎根本没有加载新页面,br.current_url仍然是'http://www.preloved.co.uk/'。

为什么这个加载不成功呢?

即使我提取了链接并明确执行GET请求,似乎也没有跟随并重新加载:

newurl=login_button.get_attribute('href')
br.get(newurl)

br.current_url仍然是'http://www.preloved.co.uk/'。

暂无标签

1 个回答

3

登录页面是通过https来保护的。最近,POODLE漏洞让很多网站不得不放弃使用SSLv3来进行https连接,但因为PhantomJS默认使用SSLv3,所以登录页面无法加载。你可以查看这个回答了解更多。

要解决这个问题,可以在启动PhantomJS时加上 --ssl-protocol=tlsv1 或者 --ssl-protocol=any,或者把PhantomJS升级到至少1.9.8版本。看起来在Selenium的Python绑定中,可以用 service_args 参数来实现这个。

不过在当前的官方实现中,service_args 似乎不能从 WebDriver 传递到PhantomJS的 Service。你可以通过子类化来解决这个问题。

from selenium import webdriver
from selenium.webdriver.phantomjs.service import Service
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver

class PhantomJSService(webdriver.PhantomJS):
    def __init__(self, executable_path="phantomjs", port=0,
                 desired_capabilities=DesiredCapabilities.PHANTOMJS,
                 service_args=None, service_log_path=None):

        self.service = Service(executable_path, 
                               port=port, service_args=service_args,
                               log_path=service_log_path)
        self.service.start()

        try:
            RemoteWebDriver.__init__(self,
                command_executor=self.service.service_url,
                desired_capabilities=desired_capabilities)
        except:
            self.quit()
            raise 

看起来这个webdriver的分支包含了设置这些选项所需的参数。

撰写回答