【问题标题】:Python : How to use find_element_by_css_selector using SeleniumPython:如何通过 Selenium 使用 find_element_by_css_selector
【发布时间】:2020-06-06 06:48:08
【问题描述】:

我正在尝试抓取新闻评论。我想从这个蓝线 HTML 代码中抓取文本“72”

所以,这是我的代码

per_male = driver.find_element_by_css_selector('div.u_cbox_chart_progress u_cbox_chart_male > 
           span.u_cbox_chart_per')
print('per_male : ' + per_male.get_attribute('text'))

但是我有这个错误

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"div.u_cbox_chart_progress u_cbox_chart_male > span.u_cbox_chart_per"}
  (Session info: chrome=83.0.4103.97)

我也用这个代码

per_male = driver.find_element_by_css_selector('div.u_cbox_chart_progress u_cbox_chart_male > 
           span.u_cbox_chart_per')
print('per_male : ' + per_male.text)

但我有同样的错误,我该如何解决这个问题?

谢谢。

【问题讨论】:

  • 请使用实际的 html 而不是图像来编辑您的问题。

标签: python-3.x selenium-webdriver xpath css-selectors webdriverwait


【解决方案1】:

要抓取文本72,您必须将WebDriverWait 诱导为visibility_of_element_located(),您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.u_cbox_chart_progress.u_cbox_chart_male>div.u_cbox_chart_per"))).text)
    
  • 使用XPATH

    print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='u_cbox_chart_progress u_cbox_chart_male']/div[@class='u_cbox_chart_per']"))).text)
    
  • 注意:您必须添加以下导入:

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

参考

您可以在NoSuchElementException 上找到一些相关讨论:

【讨论】:

  • @HyungjoonCho 很高兴能为您提供帮助。如果此答案对您有帮助,对未来的读者有帮助,请为答案投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
相关资源
最近更新 更多