提高硒代码的速度

时间:2018-02-25 18:50:27

标签: python performance selenium browser selenium-chromedriver

我在python中使用Selenium来测试数据表(不是真正的html表,由多个div组合)

那是我的桌子的样子:

<div class="products">
    <div class="product">
        <span class="original-price">20$</span>
        <span class="discounted-price">10$</span>            
    </div>

    <div class="product">
        <span class="price">20$</span>
    </div>

    ...
</div>

有多种产品,有些产品有折扣价。

这是我的剧本:

products = self.driver.find_elements_by_css_selector('.products > div')
for product in products:
    found_price = True
    try:
        original_price = product.find_element_by_css_selector('.original-price').text
        reduced_price = product.find_element_by_css_selector('.discounted-price').text
    except NoSuchElementException:
        try:
            original_price = product.find_element_by_css_selector('.price').text
            reduced_price = original_price
        except NoSuchElementException:
            found_price = False

    if found_price: check_price(original_price, reduced_price)

但是我的脚本运行得很慢。它发送了很多请求&#34; remote_connection&#34;每次&#34; find_element_by_css_selector&#34;像这样叫:

2018-02-27 13:48:08 [selenium.webdriver.remote.remote_connection] DEBUG: POST http://127.0.0.1:62147/session/14902b71a0f812fa74f81524f0eb1386/elements {"using": "css selector", "sessionId": "14902b71a0f812fa74f81524f0eb1386", "value": ".products > div .original-price"}
2018-02-27 13:48:08 [selenium.webdriver.remote.remote_connection] DEBUG: Finished Request

有任何改善其表现的想法吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

删除WebDriver的其中一个参数是\b。正如医生所说:

keep_alive

保持连接活动会提高速度,因为它不必连接每个查找请求。

答案 1 :(得分:0)

为什么您认为脚本运行速度非常慢仍然不同寻常。正如您所提到的,代码每次remote_connection 完全按照WebDriver-W3C Candidate Recommendation中定义的方式发送大量请求find_element_by_css_selector

使用Search Box的{​​{1}}进行小型测试,即Google Home Page,其中包含 WebDrivers Web浏览器的所有主要变体那个:

  • 每次在 HTML DOM 中搜索webelement时,如下所示:

    https://www.google.co.in
  • 生成以下请求:

    product.find_element_by_css_selector('.original-price')
    
  • 在成功搜索时,将从 Web浏览器发回以下响应:

    [selenium.webdriver.remote.remote_connection] DEBUG: POST http://127.0.0.1:62147/session/14902b71a0f812fa74f81524f0eb1386/elements {"using": "css selector", "sessionId": "14902b71a0f812fa74f81524f0eb1386", "value": ".products > div .original-price"}
    [selenium.webdriver.remote.remote_connection] DEBUG: Finished Request
    

您可以在Values returned by webdrivers

中找到详细的讨论
相关问题