【问题标题】:How to speed up python selenium find_elements?如何加速 python selenium find_elements?
【发布时间】:2016-06-15 01:57:15
【问题描述】:

我正在尝试从 kompass.com 抓取公司信息

但是,由于每个公司资料提供的详细信息数量不同,某些页面可能缺少元素。例如,并非所有公司都有关于“协会”的信息。在这种情况下,我的脚本需要很长时间才能搜索这些缺失的元素。无论如何我可以加快搜索过程吗?

这是我的脚本的摘录:

import time
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import ElementNotVisibleException
from lxml import html

def init_driver():
    driver = webdriver.Firefox()
    driver.wait = WebDriverWait(driver, 5)
    return driver

def convert2text(webElement):
    if webElement != []:
        webElement = webElement[0].text.encode('utf8')
    else:
        webElement = ['NA']
    return webElement

link='http://sg.kompass.com/c/mizkan-asia-pacific-pte-ltd/sg050477/'
driver = init_driver()
driver.get(link)
driver.implicitly_wait(10)

name = driver.find_elements_by_xpath("//*[@id='productDetailUpdateable']/div[1]/div[2]/div/h1")
name = convert2text(name)

## Problem:
associations = driver.find_elements_by_xpath("//body//div[@class='item minHeight']/div[@id='associations']/div/ul/li/strong")
associations = convert2text(associations)

刮掉每一页需要一分钟多的时间,我有超过 26,000 页要刮掉。

【问题讨论】:

  • 你已经导入了WebDriverWait,但尽管如此使用implicitly_wait()...为什么?

标签: python selenium selenium-webdriver web-scraping


【解决方案1】:

driver.implicitly_wait(10) 告诉驱动程序等待 10 秒以使元素存在于 DOM 中。这意味着每次您寻找不存在的元素时,它都会等待 10 秒。将时间减少到 2-3 秒将提高运行时间。

此外,xpathslowest selector,您通过提供绝对路径使其值得。尽可能使用find_elements_by_idfind_elements_by_class_name。比如你可以improve

driver.find_elements_by_xpath("//body//div[@class='item minHeight']/div[@id='associations']/div/ul/li/strong")

只需声明associations id

driver.find_elements_by_xpath("//*div[@id='associations']/div/ul/li/strong")

或者改成css_selector

driver.find_elements_by_css_selector("#associations > div > ul > li > strong")

【讨论】:

    【解决方案2】:

    由于您的 XPath 不使用除 class 和 id 之外的任何属性来查找元素,因此您可以将搜索迁移到 CSS 选择器。在不支持原生 XPath 搜索的 IE 等浏览器上,这些可能会更快。

    例如:

    //body//div[@class='item minHeight']/div[@id='associations']/div/ul/li/strong
    

    可以变成:

    body .item .minHeight > #associations > div > ul > li > strong
    

    【讨论】:

    • 似乎没有帮助。搜索丢失的元素需要相同的时间
    • @SeamusLam 你能简化一些 XPath 吗?如果以下 div 具有唯一标识符,//body//div[@class='item minHeight']/div[@id='associations']/div/ul/li/strong 肯定不需要初始的 //body//div[] 部分。
    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2014-06-08
    • 2023-01-29
    相关资源
    最近更新 更多