使用python使用Selenium进行Web抓取-不检索所有元素

使用python使用Selenium进行Web抓取-不检索所有元素,python,selenium-webdriver,xpath,css-selectors,webdriverwait,Python,Selenium Webdriver,Xpath,Css Selectors,Webdriverwait,我正在尝试使用Selenium在coinmarketcap.com上搜索,但我只能检索列表中的前10个altcoins。我读到//div[contains(concat('',normalize space(@class),'','classname'))应该可以做到这一点,但它不起作用。有人能帮我吗?我也知道coinmarketcap是一种api,但我只是想尝试另一种方法 driver = webdriver.Chrome(r'C:\Users\Ejer\PycharmProjects\py

我正在尝试使用Selenium在coinmarketcap.com上搜索,但我只能检索列表中的前10个altcoins。我读到//div[contains(concat('',normalize space(@class),'','classname'))应该可以做到这一点,但它不起作用。有人能帮我吗?我也知道coinmarketcap是一种api,但我只是想尝试另一种方法


driver = webdriver.Chrome(r'C:\Users\Ejer\PycharmProjects\pythonProject\chromedriver')
driver.get('https://coinmarketcap.com/')

Crypto = driver.find_elements_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), 'sc-16r8icm-0 sc-1teo54s-1 lgwUsc')]")
#price = driver.find_elements_by_xpath('//td[@class="cmc-link"]')
#coincap = driver.find_elements_by_xpath('//td[@class="DAY"]')

CMC_list = []
for c in range(len(Crypto)):
    CMC_list.append(Crypto[c].text)
print(CMC_list)

driver.close()

要检索列表上的前10个altcoins,您需要对所有元素的可见性进行归纳(),您可以使用以下任一选项:

  • 使用
    CSS\u选择器
    get\u属性(“innerHTML”)

  • 使用
    XPATH
    和文本属性:

    driver.get('https://coinmarketcap.com/')
    print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[contains(@class, 'cmc-table')]//tbody//tr//td/a//p[@color='text']")))[:10]])
    
  • 控制台输出:

    ['Bitcoin', 'Ethereum', 'XRP', 'Tether', 'Litecoin', 'Bitcoin Cash', 'Chainlink', 'Cardano', 'Polkadot', 'Binance Coin']
    
  • 注意:您必须添加以下导入:

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

要检索列表上的前10个altcoins,您需要对所有元素的可见性进行归纳(),您可以使用以下任一选项:

  • 使用
    CSS\u选择器
    get\u属性(“innerHTML”)

  • 使用
    XPATH
    和文本属性:

    driver.get('https://coinmarketcap.com/')
    print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[contains(@class, 'cmc-table')]//tbody//tr//td/a//p[@color='text']")))[:10]])
    
  • 控制台输出:

    ['Bitcoin', 'Ethereum', 'XRP', 'Tether', 'Litecoin', 'Bitcoin Cash', 'Chainlink', 'Cardano', 'Polkadot', 'Binance Coin']
    
  • 注意:您必须添加以下导入:

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

再次感谢您的输入,但我已经尝试检索了超过前10个alt硬币。当我使用你的代码,将10改为20,我只得到11枚硬币。另外,如果我想将值存储在空列表中,我将如何设置它。我还想检索硬币市值、价格等其他数据。@Dfhaa_DK听起来是不同的要求。你能为你的新要求提出一个新问题吗?如果你能找到我发了一个新帖子再次感谢你的意见,但我已经尝试检索了超过前10个alt硬币。当我使用你的代码,将10改为20,我只得到11枚硬币。另外,如果我想将值存储在空列表中,我将如何设置它。我还想检索硬币市值、价格等其他数据。@Dfhaa_DK听起来是不同的要求。你能为你的新要求提出一个新问题吗?如果你能找到的话,我发了一个新帖子