在python中剪切字符串变量的一部分(web抓取)

2024-10-01 07:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试抓取一个网站,因此我设法提取了我想要的所有文本,使用以下模板:

nameList = bsObj.findAll("strong")
for text in nameList:
    string = text.get_text()
    if "Title" in string:
        print(text.get_text())

我用这种方式得到文本:

标题1:TEXTTHAINED

标题2:TEXTTHAINED

标题3:文本

标题4:文本

标题5:文本

标题6:TEXTTHAINED

标题7:文本 .... 在

有没有什么方法可以让我在python中使用beautifulsoup或其他方法来剪切字符串,只得到“textsthatineed”而不带“title(number):”。在


Tags: 方法textin文本模板标题getstring
2条回答

说我们有

s = 'Title 1: textthatineed'

标题从冒号后面的两个字符开始,因此我们找到冒号的索引,向下移动两个字符,并将子字符串从该索引移到末尾:

^{pr2}$

注意,find()只返回第一次出现的索引,因此包含冒号的标题不受影响。在

在Python中,有一个非常方便的操作可以在名为slicing的字符串上完成。在

来自docs的示例

>>> word = 'Python'
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

所以你应该这样做

^{pr2}$

相关问题 更多 >