如何在python selenium webdri中获取标题

2024-05-23 15:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在selenium webdriver中获取头。类似于以下的东西:

>>> import requests
>>> res=requests.get('http://google.com')
>>> print res.headers

我需要使用Chromewebdriver,因为它支持flash和其他一些我需要测试网页的东西。以下是迄今为止我在硒中的发现:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://login.comcast.net/login?r=comcast.net&s=oauth&continue=https%3A%2F%2Flogin.comcast.net%2Foauth%2Fauthorize%3Fclient_id%3Dxtv-account-selector%26redirect_uri%3Dhttps%3A%2F%2Fxtv-pil.xfinity.com%2Fxtv-authn%2Fxfinity-cb%26response_type%3Dcode%26scope%3Dopenid%2520https%3A%2F%2Flogin.comcast.net%2Fapi%2Flogin%26state%3Dhttps%3A%2F%2Ftv.xfinity.com%2Fpartner-success.html%26prompt%3Dlogin%26response%3D1&reqId=18737431-624b-44cb-adf0-2a85d91bd662&forceAuthn=1&client_id=xtv-account-selector')
driver.find_element_by_css_selector('#user').send_keys('XY@comcast.net')
driver.find_element_by_css_selector('#passwd').send_keys('XXY')
driver.find_element_by_css_selector('#passwd').submit()
print driver.headers ### How to do this?

我已经看到了其他一些建议运行整个selenium服务器来获取这些信息的答案(https://github.com/derekargueta/selenium-profiler)。如何使用类似于上面的Webdriver来获得它?


Tags: importcomgetbynetdriverseleniumres
3条回答

您可以尝试Mobilenium,一个绑定BrowserMob代理和Selenium的python包(仍在开发中)。

用法示例:

>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'

您可以通过日志获取头(来源于Mma's answer

from selenium import webdriver
import json
driver = webdriver.PhantomJS(executable_path=r"your_path")
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('headers: ', har['log']['entries'][0]['request']['headers'])

不幸的是,您无法从Selenium webdriver获取此信息,您也无法在不久的将来获得任何信息。摘自a very long conversation on the subject

This feature isn't going to happen.

主要原因的要点是,根据我从讨论中得到的信息,webdriver是用来“驱动浏览器”的,并且在开发人员看来,扩展API超过这个主要目标将导致API的总体质量和可靠性受到影响。

在许多地方,包括上面链接的对话中,我看到了一个可能的解决方法,即使用BrowserMob Proxy(可以用来捕获HTTP内容)和can be used with selenium(尽管链接的示例不使用Python selenium API)。似乎确实有a Python wrapper for BrowserMob Proxy,但我无法保证它的功效,因为我从未使用过它。

相关问题 更多 >