【发布时间】:2021-07-04 22:03:10
【问题描述】:
我尝试了许多不同的 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()
【问题讨论】:
标签: python web-scraping xpath scrapy