Xpath 和 CssSelector 不使用 Selenium 和 Python 提取数据

Xpath and CssSelector not extracting data using Selenium and Python

我正在尝试将所有列表拉到主要部分的顶部(在本例中,它目前显示 72 个列表)。我试过 By.XPATHBy.CSS_SELECTOR 都没有运气....知道为什么这不起作用吗?

driver.get('https://swappa.com/mobile/buy/apple-iphone-8/att')
n = WebDriverWait(driver, 0.01).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".col-xs-9 pull-left"))).text

要打印 text 72 Listings 您可以使用以下任一方法 :

  • 使用 css_selectorget_attribute("innerHTML"):

    print(driver.find_element_by_css_selector("section#section_billboard h2 small").get_attribute("innerHTML"))
    
  • 使用 xpathtext 属性:

    print(driver.find_element_by_xpath("//section[@id='section_billboard']//h2//small").text)
    

理想情况下,您需要为 visibility_of_element_located() 引入 ,您可以使用以下任一方法 :

  • 使用 CSS_SELECTORtext 属性:

    driver.get('https://swappa.com/mobile/buy/apple-iphone-8/att')
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "section#section_billboard h2 small"))).text)
    
  • 使用 XPATHget_attribute():

    driver.get('https://swappa.com/mobile/buy/apple-iphone-8/att')
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//section[@id='section_billboard']//h2//small"))).get_attribute("innerHTML"))
    
  • 控制台输出:

    value
    
  • 注意:您必须添加以下导入:

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

You can find a relevant discussion in


参考资料

Link 到有用的文档:

  • get_attribute()方法Gets the given attribute or property of the element.
  • text属性returnsThe text of the element.
  • Difference between text and innerHTML using Selenium