在Python2.x中拆分URL

2024-05-23 21:05:20 发布

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

我有一个链接在一些HTML代码中被解析为下图:-你知道吗

"http://advert.com/go/2/12345/0/http://truelink.com/football/abcde.html?"

我要做的是从第二次出现http开始提取代码的第二部分:所以在上面的例子中,我想提取

"http://truelink.com/football/abcde.html?"

我已经考虑过将URL分割成段,但是我不确定随着时间的推移,第一部分的结构是否会保持不变。你知道吗

有没有可能识别第二个出现的“http”,然后从那里解析代码到底?你知道吗


Tags: 代码comhttpurlgo链接html时间
2条回答
link = "http://advert.com/go/2/12345/0/http://truelink.com/football/abcde.html?"

link[link.rfind("http://"):]

退货:

"http://truelink.com/football/abcde.html?"

这就是我要做的。rfind查找最后出现的“http”并返回索引。 在您的示例中,这种情况显然是真实的、原始的url。然后可以提取从该索引开始到结束的子字符串。你知道吗

因此,如果您有一些字符串myStr,则在python中使用类似数组的表达式提取子字符串:

myStr[0]    # returns the first character
myStr[0:5]  # returns the first 5 letters, so that 0 <= characterIndex < 5
myStr[5:]   # returns all characters from index 5 to the end of the string
myStr[:5]   # is the same like myStr[0:5]

我会这样做:

addr = "http://advert.com/go/2/12345/0/http://truelink.com/football/abcde.html?"
httpPart = 'http://'
split = addr.split(httpPart)
res = []
for str in split:
    if (len(str) > 0):
        res.append(httpPart+str);
print res

相关问题 更多 >