Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用re.sub将selenium字符串转换为整数_Python_Selenium_Integer_Substring_Typeerror_Re - Fatal编程技术网

Python 如何使用re.sub将selenium字符串转换为整数

Python 如何使用re.sub将selenium字符串转换为整数,python,selenium,integer,substring,typeerror,re,Python,Selenium,Integer,Substring,Typeerror,Re,在他生命的最后几天里,我非常渴望将我的字符串值转换为整数,所以我尝试以下方法: 快照: 代码试用: follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span').text) convert_follower_count = re.sub('[^0-9]','', follower_count) 。。。不起作用: Tr

在他生命的最后几天里,我非常渴望将我的字符串值转换为整数,所以我尝试以下方法:

快照:

代码试用:

follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span').text)
convert_follower_count = re.sub('[^0-9]','', follower_count)
。。。不起作用:

Traceback (most recent call last):
 File "C:\Users\Desktop\TwitPy\quickstart.py", line 79, in <module>
   followers_count = re.sub('[^0-9]','', follower_count)
 File "C:\Users\AppData\Local\Programs\Python\Python38\lib\re.py", line 208, in sub
   return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object          
回溯(最近一次呼叫最后一次):
文件“C:\Users\Desktop\TwitPy\quickstart.py”,第79行,在
追随者计数=re.sub(“[^0-9]”,“,”,追随者计数)
文件“C:\Users\AppData\Local\Programs\Python\Python38\lib\re.py”,第208行,子文件
return\u compile(模式、标志).sub(repl、字符串、计数)
TypeError:应为字符串或类似字节的对象

此处的类型错误是因为您已将follower\u count转换为整数,然后将其传递给仅接受字符串或字节类对象的re.sub。 您应该检查browser.find_element_by_xpat的输出,看看它是否是字符串。如果是,您不应该遇到任何错误。如果是selenium中的列表或对象,您可能需要做的不仅仅是将follower_count传递给re.sub

follower_count = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span').text
convert_follower_count = int(re.sub('[^0-9]','', follower_count))

提取的文本,即1961包含一个
字符。因此,您将无法直接在其上调用
int()


解决方案 您可以使用
sub()

  • 代码块:

    # follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span').text)
    count = "1,961"
    
    import re
    print(int(re.sub(',', '', count)))
    print(type(int(re.sub(',', '', count))))
    
  • 控制台输出:

    1961
    <class 'int'>
    

    工具书类 有关详细讨论,请参见:


    您的
    follower\u count
    是一个int。您不能替换其中的字符,因为它不包含字符。这是一个数字。
    follower_count = int(re.sub(',', '', browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span').text))