我正在尝试从 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 多页要抓取。
最佳答案
driver.implicitly_wait(10)
告诉驱动程序最多等待 10 秒,以便元素存在于 DOM 中。这意味着每次您寻找不存在的元素时,它都会等待 10 秒。将时间减少到 2-3 秒将缩短运行时间。
此外,xpath
是 slowest selector ,并且您通过提供绝对路径使其物有所值。尽可能使用 find_elements_by_id
和 find_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")
关于python - 如何加速 python selenium find_elements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35743417/