Python+Selenium中级篇之7-Python中字符串切割操作

      本文来介绍Python中字符串切割操作,在Python中自带的一个切割方法split(),这个方法不带参数,就默认按照空格去切割字段,如果带参数,就按照参数去切割。为了演示切割效果,我们用百度搜索一个关键字,然后去找一共找到了多个结果的数字。

      例如,百度搜索“selenium”,查看找到了多少个结果,我们需要单独摘取出这个数字。

Python+Selenium中级篇之7-Python中字符串切割操作_第1张图片

相关脚本代码如下:

# coding=utf-8
import time
from selenium import webdriver


class GetSubString(object):

    def get_search_result(self):
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.implicitly_wait(8)

        driver.get('https://www.baidu.com')
        driver.find_element_by_id('kw').send_keys('selenium')
        time.sleep(1)
        search_result_string = driver.find_element_by_xpath("//*/div[@class='nums']").text
        print (search_result_string)

        new_string = search_result_string.split('约')[1] # 第一次切割得到 xxxx个,[1]代表切割右边部分
        print (new_string)
        last_result = new_string.split('个')[0]  # 第二次切割,得到我们想要的数字 [0]代表切割参照参数的左边部分
        print (last_result)


getstring = GetSubString()
getstring.get_search_result()


你可能感兴趣的:(Python+Selenium中级篇之7-Python中字符串切割操作)