【问题标题】:Selenium convert format number " k " (thousand) python to get titleSelenium 转换格式数“k”(千)python 获取标题
【发布时间】:2021-05-15 17:58:52
【问题描述】:

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

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

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

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

【问题讨论】:

  • xpath 看起来无效。请显示带有可运行代码的minimal reproducible example,并将标记显示为文本,而不是屏幕截图。谢谢。
  • .get_attribute('title') 会产生 170,125,然后只需使用 .replace(",","") 你会得到 170125 然后你使用 int。

标签: python selenium selenium-webdriver type-conversion integer


【解决方案1】:

您可以通过以下多种方式替换“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'>
    

参考

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

【讨论】:

    【解决方案2】:

    我认为问题出在您的 xpath 上。这对我来说似乎不正确。 重新勾选,使用get_attribute()获取title的值,去掉“,”,然后转换为int数据类型。

        driver.get("https://www.instagram.com/barked/")
        
        # get title value
        follower = driver.find_element_by_xpath("//header/section/ul/li/a/span")
        .get_attribute("title")
        
        # replace the , and convert to int data type
        number_of_follower = int(str(follower).replace(",", ""));
    
        print(follower)
        print(number_of_follower)
    

    然后你会得到以下结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多