【问题标题】:How to scrape data from webpage which uses react.js with Selenium in Python?如何从 Python 中使用 react.js 和 Selenium 的网页中抓取数据?
【发布时间】:2020-01-01 11:48:38
【问题描述】:

我在抓取使用 react.js 的网站时遇到了一些困难,但不知道为什么会这样。

这是网站的html:

我想做的是单击带有class: play-pause-button btn btn -naked 的按钮。但是,当我使用 Mozilla gecko webdriver 加载页面时,会抛出一个异常,说

Message: Unable to locate element: .play-pause-button btn btn-naked

这让我觉得也许我应该做点别的来获得这个元素? 到目前为止,这是我的代码:

driver.get("https://drawittoknowit.com/course/neurological-system/anatomy/peripheral-nervous-system/1332/brachial-plexus---essentials")
    # execute script to scroll down the page
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
    time.sleep(10)        
    soup = BeautifulSoup(driver.page_source, 'lxml')
    print(driver.page_source)
    play_button = driver.find_element_by_class_name("play-pause-button btn btn-naked").click()
    print(play_button)

有人知道我该如何解决这个问题吗?非常感谢任何帮助

【问题讨论】:

    标签: python reactjs selenium web-scraping webdriverwait


    【解决方案1】:

    看来你很接近了。在使用find_element_by_class_name() 时,您不能传递多个,并且只允许传递一个类名,即只能传递其中一个以下:

    • play-pause-button
    • btn
    • btn-naked

    在通过find_element_by_class_name() 传递多个课程时,您将面临Message: invalid selector: Compound class names not permitted


    解决方案

    作为替代方案,由于元素是 Angular 元素,因此您必须为 element_to_be_clickable() 诱导 WebDriverWait 元素上的 click() 并且您可以使用以下任一种Locator Strategies:

    • 使用CSS_SELECTOR

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.play-pause-button.btn.btn-naked")))click()
      
    • 使用XPATH:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='play-pause-button btn btn-naked']")))click()
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 2022-08-18
      • 2012-01-28
      • 1970-01-01
      相关资源
      最近更新 更多