如何使用re.sub将硒字符串转换为整数 [英] How use re.sub to convert selenium string to an Integer
本文介绍了如何使用re.sub将硒字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的很希望他的最后几天将我的字符串值转换为整数,所以我尝试这样做:
快照:
代码试用:
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(最近一次通话最近):< module>中的文件"C:\ Users \ Desktop \ TwitPy \ quickstart.py",第79行.followers_count = re.sub('[^ 0-9]','',follower_count)子目录中的文件"C:\ Users \ AppData \ Local \ Programs \ Python \ Python38 \ lib \ re.py",第208行返回_compile(pattern,flags).sub(repl,string,count)TypeError:预期的字符串或类似字节的对象
解决方案
提取的文本(即 1,961 )之间包含一个
字符.因此,您将无法直接在其上调用 int()
.
解决方案
您可以使用sub()tag> re 替换文本 1,961 中的,
字符,然后按如下所示调用 int()
:>
-
代码块:
#follower_count = int(browser.find_element_by_xpath('/html/body/div [1]/section/main/div/header/section/ul/li [2]/a/span').text)计数="1,961".汇入print(int(re.sub(',','',count)))print(type(int(re.sub(',',``,count)))))
-
控制台输出:
1961< class'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))
参考文献
您可以在以下位置找到相关的详细讨论:
I am really desperate his last days to convert my string numbers value to a integer, so i try this :
Snapshot:
Code trials:
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)
... is not working :
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
解决方案
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 can can use sub()
from re to replace the ,
character from the text 1,961 first and then invoke int()
as follows:
Code Block:
# 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))))
Console Output:
1961 <class 'int'>
This usecase
Effectively, your line of code will be:
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))
References
You can find a relevant detailed discussion in:
这篇关于如何使用re.sub将硒字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文