如何使用Selenium

时间:2018-01-25 21:26:30

标签: python selenium click

我一直试图通过反复点击按钮'显示6条评论' 来抓取单个网址上的所有评论。我相信这个问题适用于任何人使用Selenium在一个网址上删除许多动态元素。

问题:当评论数量超过几百时,循环变得非常慢。 我正在使用Selenium,因为该网站涉及Javascript。

按钮的HTML我点击(朝向页面底部)

<button type="button" class="css-1e0935c" data-comp="Link Box">Show 6 more reviews<svg viewBox="0 0 95 57" class="css-1ymrwr7" data-comp="Chevron Box"><path d="M47.5 57L95 9.5 85.5 0l-38 38-38-38L0 9.5 47.5 57z"></path></svg></button>

我尝试的事情:

我想到的事情:

  • 使用PhantomJS替换Chrome。我有问题滚动 PhantomJS。我没有追求,因为它似乎会获得收益 增量,而不是我需要的数量级(我可能是错的)。
  • 在评论可用时加载评论,而不是在整个页面被扩展时加载#39;我不这么认为 将解决性能问题
  • 找到一种更快速地解析按钮的方法。我读到了how browsers match CSS selectors,但无法找到改进代码的方法

这是我的第一个问题。非常感谢您的耐心和帮助。

python 2或3中的可重现代码(慢循环位于底部):

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
import time

# Page with 5591 reviews
url = "https://www.sephora.com/product/soy-face-cleanser-P7880?icid2=:p7880:product"

driver = webdriver.Chrome()
driver.get(url)
time.sleep(4)

# Navigation steps  (feel free to skip)
# scroll to section 'Similar Products' (above Reviews)
timeout = 10
wait_driver = WebDriverWait(driver, timeout)
section_title = wait_driver.until(EC.presence_of_element_located(\
        (By.XPATH, '//h2[@class="css-1orm38z"]')))
driver.execute_script("arguments[0].scrollIntoView();", section_title)
# Sort by newest review
wait_driver.until(EC.presence_of_element_located(\
        (By.XPATH, '//button[@class="css-u2mtre"]'))).click()
wait_driver.\
    until(EC.presence_of_element_located(\
        (By.XPATH, '//div/span[text()="Newest"]'))).click()

# This is the loop that is way too slow

# First expand all reviews by clicking button
numReviews = 0
while True:
    try:
        # Fastest selector I could come up with
        button = driver.find_element_by_css_selector(' .css-1e0935c')
        button.click()

        numReviews += 6
        print("Loading 6 more reviews... (" + str(numReviews) + ")")

    except Exception:
        break

# Now that full page is loaded, store all reviews
# [...]

输出:

Loading 6 more reviews... (6)
Loading 6 more reviews... (12)
Loading 6 more reviews... (18)
Loading 6 more reviews... (24)
Loading 6 more reviews... (30)
Loading 6 more reviews... (36)
Loading 6 more reviews... (42)
Loading 6 more reviews... (48)
Loading 6 more reviews... (54)
Loading 6 more reviews... (60)
Loading 6 more reviews... (66)
Loading 6 more reviews... (72)
Loading 6 more reviews... (78)
Loading 6 more reviews... (84)

...等 我的程序适用于200条评论的产品,但随着评论数量的增加,上述时间会越来越多(例如,我的示例网址中的大小为5000)。

0 个答案:

没有答案