如何在Scrapy中为以下html编写css选择器

ugmeyewa  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(151)

我想获取td标记下p标记中写入的金额,但我获取的是p元素内容作为字符串,我只想提取写入的金额。
HTML代码:

我使用的命令:

response.css("#__next > div > div:nth-child(2) > div > div.data-table_container__pPKXQ > table > tbody > tr:nth-child(1) > td:nth-child(3) > p: nth-child(1)").get()
tag5nh1u

tag5nh1u1#

使用xpath:

In [1]: all_tr = response.xpath('//tbody/tr')

In [2]: for example in all_tr:
   ...:     print(example.xpath('./td/p/text()[2]').get())
   ...:
$533.2M
$10.4B
$811.5M
$518.8M
$39.6M
$264.7M
$390M
$3.2B
$508.1M
$404.3M
$7.4B
$410.3M
$14.2M
$33.3M
$11.9M
$1.4B
$745.2M
$1.9B
$70M
$72.7M
$580M
$100.2M
$1.8B
$143.4M
$150M

使用CSS:

In [1]: all_tr = response.css('tbody > tr')

In [2]: for example in all_tr:
   ...:     print(example.css('td > p::text').getall()[1])
   ...:
$533.2M
$10.4B
$811.5M
$518.8M
$39.6M
$264.7M
$390M
$3.2B
$508.1M
$404.3M
$7.4B
$410.3M
$14.2M
$33.3M
$11.9M
$1.4B
$745.2M
$1.9B
$70M
$72.7M
$580M
$100.2M
$1.8B
$143.4M
$150M
0x6upsns

0x6upsns2#

您需要选择所需的属性,在您的情况下将是文本。
::text添加到css选择器的末尾。

response.css("#__next > div > div:nth-child(2) > div > div.data-table_container__pPKXQ > table > tbody > tr:nth-child(1) > td:nth-child(3) > p: nth-child(1)::text").get()

如果您试图从表中的所有行获取相同的值,那么您的选择器也可以简化。
例如:

response.xpath("//tr/td/p/text()").getall()

另请查看超级用户答案中的示例

相关问题