如何用BeautifulSoup或Selenium获取CoinMarketCap页面指定链接
解决方案:获取CoinMarketCap币种页面的Website与Whitepaper链接
由于CoinMarketCap页面结构频繁变更,依赖class选择器的旧代码容易失效,以下两种基于文本匹配的方案更稳定,只要页面上的链接名称("Website"、"Whitepaper")不变就能正常工作:
方案一:使用BeautifulSoup
通过直接匹配链接文本定位目标元素,同时添加请求头绕过基础反爬:
from bs4 import BeautifulSoup import requests url = 'https://coinmarketcap.com/currencies/bob/' # 添加User-Agent模拟浏览器请求,避免被反爬拦截 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') # 获取Website链接 website_tag = soup.find('a', string='Website') if website_tag: print(f"Website: {website_tag['href']}") # 获取Whitepaper链接 whitepaper_tag = soup.find('a', string='Whitepaper') if whitepaper_tag: print(f"Whitepaper: {whitepaper_tag['href']}")
方案二:使用Selenium
适合已经在用Selenium操作页面的场景,利用显式等待确保元素加载完成:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url = 'https://coinmarketcap.com/currencies/bob/' # 初始化Chrome浏览器(需提前配置对应版本的chromedriver) driver = webdriver.Chrome() driver.get(url) try: # 等待Website链接加载完成并获取 website_elem = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.LINK_TEXT, 'Website')) ) print(f"Website: {website_elem.get_attribute('href')}") # 等待Whitepaper链接加载完成并获取 whitepaper_elem = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.LINK_TEXT, 'Whitepaper')) ) print(f"Whitepaper: {whitepaper_elem.get_attribute('href')}") finally: # 关闭浏览器 driver.quit()
注意事项
- 若使用BeautifulSoup时仍无法获取内容,可尝试更新
User-Agent为当前浏览器的最新标识; - Selenium需确保chromedriver版本与本地Chrome浏览器版本一致。
内容的提问来源于stack exchange,提问作者Alessandro Bitetto
相关产品推荐
相关产品推荐

