python - 我如何在网络上抓取某些没有附加属性的单词?
问题描述
首先,我想指出我是网络抓取的初学者。我刚刚开始一个从https://coinmarketcap.com刮取数据的项目。目前,我专注于抓取加密货币的名称(即比特币、以太坊、Tether 等)。但是,我能得到的最好的结果是货币的名称,后跟一堆格式,如颜色、字体大小、类等。我该如何编码,以便我可以只存储货币的名称而没有这个额外的信息。这是我当前的代码:
import requests
from bs4 import BeautifulSoup
#array of just crypto names
names = []
#gets content from site
site = requests.get("https://coinmarketcap.com")
#opens content from site
info = site.content
soup = BeautifulSoup(info,"html.parser")
#class ID for name of crypto
type_name = 'sc-1eb5slv-0 iJjGCS'
#crypto names + other unnecessary info
names_raw = soup.find_all('p', attrs={'class': 'sc-1eb5slv-0 iJjGCS'})
for type_name in names_raw:
print(type_name.text, type_name.next_sibling)
如果图片更有用: 我当前的代码
如您所见,我只有 20 行,但很难弄清楚这一点。我很感激你能给我的任何帮助或建议。
解决方案
要从此页面获取加密货币的名称和代码,您可以使用下一个示例:
import requests
from bs4 import BeautifulSoup
url = "https://coinmarketcap.com"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
for td in soup.select("td:nth-of-type(3)"):
t = " ".join(tag.text for tag in td.select("p, span")).strip()
print("{:<30} {:<10}".format(*t.rsplit(maxsplit=1)))
印刷:
Bitcoin BTC
Ethereum ETH
Tether USDT
Binance Coin BNB
Cardano ADA
XRP XRP
USD Coin USDC
Dogecoin DOGE
Polkadot DOT
Binance USD BUSD
Uniswap UNI
Bitcoin Cash BCH
Litecoin LTC
Chainlink LINK
Solana SOL
Wrapped Bitcoin WBTC
Polygon MATIC
Ethereum Classic ETC
Stellar XLM
THETA THETA
...and so on.
推荐阅读
- html - 为什么 mapbox 没有正确加载地图?
- python - FileNotFoundError: [Errno 2] No such file or directory: ' ' ---> 引用让我失望
- java - 在 bitbucket 管道上执行 gradle 后出现“无法完成 Gradle Test Executor 2 的执行”错误
- python - 计算两个二维图像的频率分量之间的互信息(Python)
- javascript - 寻找时间和空间有效的算法将任何整数转换为二进制值
- javascript - 如何在 div 的角落创建弯曲边框?
- java - 当@PrepareForTest 注释传递参数是子(扩展)类时,PowerMock 引发异常
- css - CSS 网格的滑块 - 为什么滑动网格时会出现失真?
- python - 可重新排序的列表视图不调用 removeRows()
- python - TypeError:“NoneType”对象在装饰器中不可调用