pythonurllib模块:遍历URL

2024-10-01 13:44:13 发布

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

我试图从页面的html文本中获取最后5个字符,并用它们替换url中的最后5个字符,然后再试一次。我需要重复多次。在

这就是我想出来的。目前,它连续打印同一个url 5次。在

import urllib.request

prevurl = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
for i in range(1,5):
    with urllib.request.urlopen(prevurl) as url:
        s = url.read()
        prevurl.replace('[-5:]', 's[-5:]')
    print(prevurl)

Tags: 文本importcomhttpurlrequestdefhtml
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:13

我不明白为什么会有负面影响。我可以用一些建设性的批评来代替。鼓励学习的好方法。在

不管怎样,我想我知道了。它需要一些额外的步骤,但工作方式正是我想要的。在

import urllib.request

prevurl = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
for i in range(1,400):
    with urllib.request.urlopen(prevurl) as url:
        s = url.read().decode("utf-8")
        n1 = []
        u1 = []
        for i in s:
            if i.isdigit():
                n1.append(i)
                n2 = ''.join(n1)
        for i in prevurl:
            if i.isdigit():
                u1.append(i)
                u2 = ''.join(u1)
        if len(n2) != len(u2):
            prevurl = prevurl.replace(prevurl[-(len(u2)):], n2)
        else:
            prevurl = prevurl.replace(prevurl[-(len(n2)):],n2)

    print(prevurl)

相关问题 更多 >