Skip to content Skip to sidebar Skip to footer

Convert A Scraped String Containing Comma Into An Integer Using Python

Im trying to scrape the number of followers count with selenium but it clearly identify the 'ValueError' as a number: Snapshot: Code trials: follower_count =int(browser.find_eleme

Solution 1:

The extracted text i.e. 1,961 contains a , character in between. So you won't be able to invoke int() directly on it.


Solution

You need to replace() the , character from the text 1,961 first and then invoke int() as follows:

  • Code Block:

    # count = browser.find_element_by_xpath('/html/body/div/div/div/div[2]/main/div/div/div/div[1]/div/div[2]/div/div/div[1]/div/div[5]/div[2]/a/span[1]/span').text
    count = "1,961"print(int(count.replace(",","")))
    print(type(int(count.replace(",",""))))
    
  • Console Output:

    1961
    <class'int'>
    

This usecase

Effectively, your line of code will be:

follower_count =int(browser.find_element_by_xpath('/html/body/div/div/div/div[2]/main/div/div/div/div[1]/div/div[2]/div/div/div[1]/div/div[5]/div[2]/a/span[1]/span').text.replace(",",""))
following_count = int(browser.find_element_by_xpath('/html/body/div/div/div/div[2]/main/div/div/div/div[1]/div/div[2]/div/div/div[1]/div/div[5]/div[1]/a/span[1]/span').text.replace(",",""))

References

You can find a relevant detailed discussion in:

Post a Comment for "Convert A Scraped String Containing Comma Into An Integer Using Python"