刮擦返回表中第 10 行之后的'None'



我尝试了许多不同的xpath表达式,但无法完全实现。基本上,我会得到表中前10行的文本,然后是后面90行的"无"。如果我做一个不同的xpath表达式(有人建议我做这个表达式,但我个人并不完全理解(,它会给出最后90个,而不是前10个。一开始我以为是tbody造成的,所以我把它从xpath表达式中删除了。我所针对的标签的类在第10行之后也发生了变化,所以我不确定这是否有什么不同。我试着插入一个";或";语句,试图获得两个xpath中最好的一个,但它的位置似乎不正确。请帮忙!

class CryptocurrenciesSpider(scrapy.Spider):
name = 'cryptocurrencies'
allowed_domains = ['www.coinmarketcap.com']
def start_requests(self):
yield scrapy.Request(url='https://www.coinmarketcap.com/', callback=self.parse)

#Udemy Answer. Yields last 90 with 'None' for the first 10 rows. 
def parse(self, response):
for row in response.xpath("//table//tr"):
currency = row.xpath(".//td/a/span[2]/text()").get()
if currency:
yield {
'currency': currency
}
#Yields the first 10 and then 'None' for the rest.
def parse(self, response):
for row in response.xpath(".//table//tr"):
yield {
'Currency': row.xpath(".//td[3]/div/a/div/div/p/text()").get()
}
# Tried the "or" operator to no avail.
# row.xpath(".//td[3]/div/a/div/div/p/text() or .//td/a/span[2]/text()").get(
# row.xpath(".//td[3]/div/a/div/div/p/text()" or ".//td/a/span[2]/text()").get()

Jacob,

事实上,解决方案已经掌握在你手中。

您有前十行以及后面九十行的xpath表达式。你所需要做的就是把它们结合起来。

我建议您尝试管道|,它用作联合运算符。

.getall()获取完整100个名称的整个xpath可能是下面的lengthy beast

//table[contains(@class, "cmc-table")]//tr/td[3]//a/div/div/p/text() | //table[contains(@class, "cmc-table")]//tr/td[3]//a/span[2]/text()

或者,您可能希望对行/列/锚部分进行迭代,并仅对更改的部分使用并集。

祝你好运,玩得开心!

使用requestsjson库。您将不必担心元素的xpath。您将轻松获得这些数据。下面的东西-

req = requests.get('https://api.coinmarketcap.com/data-api/v3/cryptocurrency/listing?start=1&limit=100&sortBy=market_cap&sortType=desc&convert=USD,btc,eth&cryptoType=all&tagType=all&aux=ath,atl,high24h,low24h,num_market_pairs,cmc_rank,date_added,tags,platform,max_supply,circulating_supply,total_supply,volume_7d,volume_30d',
headers={'Accept': 'application/json','Content-Type': 'application/json'})
if(req.status_code == 200):
josn2 = req.json()
currencyDetails = josn2['data']['cryptoCurrencyList']
print(len(currencyDetails))
for i in currencyDetails:
print("name : " + i.get('name'), "ttSymbol : "+ i.get('symbol'))

您将需要以下进口-

import requests
import json

输出-

100
name : Bitcoin      Symbol : BTC
name : Ethereum         Symbol : ETH
name : Binance Coin         Symbol : BNB
name : XRP      Symbol : XRP
name : Tether       Symbol : USDT
name : Cardano      Symbol : ADA
name : Polkadot         Symbol : DOT
name : Uniswap      Symbol : UNI

最新更新