- 截取字符串中的地址,其它字符类似
- <a href="https://www.meishij.net/zuofa/baiqieji_33.html" class="list_s2_item_img" style="background:url(https://s1.st.meishij.net/r/41/203/113291/s113291_154337576945105.jpg) center no-repeat;background-size:cover;"></a>
- 要截取上面云代码中url地址
- 方法1,使用split()截取
-
food_picture=str(each.xpath('./div/a[1]/@style')).split('(')[-1].split(')')[0]
- 因为xpath返回的是列表所以加上str,转变成字符串(暂时方法)
- 第一个split()以截取xpath中@style得到的值,以'('截取两个字符串,[-1]表示最后一个,获得"https://s1.st.meishij.net/r/41/203/113291/s113291_154337576945105.jpg) center no-repeat;background-size:cover"
- 第二个split()在获得的字符串中找到')'截取字符串,[0]表示第一个字符串
- 输出为:https://s1.st.meishij.net/r/41/203/113291/s113291_154337576945105.jpg
- 方法2,使用切片的方法截取短的字符串
-
>>> s="hello world" >>> index=s[0:5] >>> index 'hello' >>>
-
有其它方法补充
Python中使用split()截取字符串的方法
最新推荐文章于 2024-08-11 03:24:30 发布