首页 > 解决方案 > Selenium 转换格式数“k”(千)python 获取标题

问题描述

我想用 selenium 提取,instagram 上的数字追随者,但“k”格式(千)阻止我得到这个。

在此处输入图像描述

所以我在 python 上尝试了这个:

 follower_count = int(browser.find_element_by_xpath("//li//a//span[contains(@title]").text)

但它不起作用,我认为要么用整数替换“k”,要么使用find_element_by_xpath()提取标题上的“int”

标签: pythonseleniumselenium-webdrivertype-conversioninteger

解决方案


您可以通过多种方式替换“k”格式(千),如下所示:

  • 使用innerTextreplace()方法:

    # follower_count = browser.find_element_by_xpath("//li//a//span[contains(@title)]").text
    follower_count = "170k"
    print(int(follower_count.replace("k","000")))
    # 170000
    print(type(int(follower_count.replace("k","000"))))
    # <class 'int'>
    
  • 使用title属性和re.sub()方法:

    # follower_count = browser.find_element_by_xpath("//li//a//span[contains(@title)]").get_attribute("title")
    import re
    follower_count = "170,125"
    print(int(re.sub(',', '', follower_count)))
    # 170125
    print(type(int(re.sub(',', '', follower_count))))
    # <class 'int'>
    

参考

您可以在以下位置找到一些相关的详细讨论:


推荐阅读