为什么selenium webdriver会在每次函数调用时访问网络?

gal*_*ant 2 python selenium webdriver phantomjs

在Python中使用selenium webdriver编写了一个简单的测试函数:

from selenium import webdriver

def test_webdriver():
    web = webdriver.PhantomJS()
    web.get('http://example.com')
    web.find_element_by_tag_name('html')
    web.find_element_by_tag_name('head')
    web.find_element_by_tag_name('meta')
    web.find_element_by_tag_name('body')
    web.find_element_by_tag_name('title')
    web.find_element_by_tag_name('p')
    web.find_element_by_tag_name('div')
Run Code Online (Sandbox Code Playgroud)

这个函数花比预期更长的时间来运行,所以我用cProfile对它进行了分析,看到了一些这样的行:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      ...
        9    0.000    0.000    0.157    0.017 .../python2.7/urllib2.py:386(open)
      ...
Run Code Online (Sandbox Code Playgroud)

这清楚地表明webdriver正在我的测试功能中的每次 find调用中访问网络.

我认为webdriver一次只抓取一次DOM get(),然后在本地搜索和操作它,类似于BeautifulSoup.显然它不是那样工作所以我留下了一些问题:

  • 这是webdriver的正常预期行为,还是我的错误配置?
  • 如果这正常行为,那么有没有办法强制webdriver 在每次函数调用时都不访问网络?
  • 什么是访问网络?它不能刷新每一页find,只是没有任何意义.

注意:我知道测试页面上的javascript可能会触发非预期的网络呼叫,这就是我使用http://example.com作为我的测试页面的原因,以消除这种可能性.

Art*_*ure 5

我相信WebDriver和浏览器之间的通信是通过网络连接进行的:https://code.google.com/p/selenium/wiki/JsonWireProtocol

因此,虽然它肯定没有向example.com发出九个请求,但它仍然可以向WebDriver发出九个本地网络请求 - 在您的示例中,这是一个配置浏览器,一个要求浏览器执行GET,以及七个内部查询页面DOM.

应该有一些方法可以让您的WebDriver客户端库记录它对浏览器的实际调用.