I am trying to web scrape coinmarketcap.com using Selenium, but I can only retrieve the first 10 altcoins on the list. I read that //div[contains(concat(' ', normalize-space(@class), ' '), 'class name')] should do the trick, but it is not working. Can someone help me? I am also aware that coinmarketcap as an api, but I just wanted to try another way.
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()
To retrieve the first 10 altcoins on the list you need to induce WebDriverWait for the visibility_of_all_elements_located()
and you can use either of the following Locator Strategies :
Using CSS_SELECTOR
and get_attribute("innerHTML")
:
driver.get('https://coinmarketcap.com/') print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table.cmc-table tbody tr td > ap[color='text']")))[:10]])
Using XPATH
and text attribute:
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]])
Console Output:
['Bitcoin', 'Ethereum', 'XRP', 'Tether', 'Litecoin', 'Bitcoin Cash', 'Chainlink', 'Cardano', 'Polkadot', 'Binance Coin']
Note : You have to add the following imports:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.