def extract_totalrecord(self):
search_result_string =self.driver.find_element_by_xpath("//*/div[@class='nums']").text
new_string = search_result_string.split('约')[1] //调用split 函数
last_result = new_string.split('个')[0]
num = re.sub(r',', "", last_result) # sub函数用于替换字符串中的匹配项。
return num
a = baidu.extract_totalrecord()
#判断返回的字符串是否为纯数字
方法一:通过isdigit()函数
m = a.isdigit()
方法二:pattern.match()方法:
这个方法将在字符串string的pos位置开始尝试匹配pattern(pattern就是通过re.compile()方法编译后返回的对象),如果pattern匹配成功,无论是否达到结束位置endpos,都会返回一个匹配成功后的Match对象;如果匹配不成功,或者pattern未匹配结束就达到endpos,则返回None。
参数说明:
string:被匹配的字符串
pos:匹配的起始位置,可选,默认为0
endpos:匹配的结束位置,可选,默认为len(string)
匹配到的Match对象,我们将使用其具有的group()方法取出匹配结果。
re.match方法从头开始匹配,匹配不到就返回None
pattern.match和re.match的区别是pattern.match可以指定匹配的起始位置。
e.g. pattern = re.compile(r'^[-+]?[0-9]+$')
result = pattern.match(a)
方法三:re.match()方法
该函数的作用是尝试从字符串string的起始位置开始匹配一个模式pattern,如果匹配成功返回一个匹配成功后的Match对象,否则返回None。
参数说明:
pattern:匹配的正则表达式
string:要匹配的字符串
flags:标志位,用于控制正则表达式的匹配方式。如是否区分大小写、是否多行匹配等。
result = re.match(pattern, a)
共同部分:
if result:
print ("Result is a number.")
else:
print("Result is not a number")