微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在自己的输出上重复一个python函数

如何解决在自己的输出上重复一个python函数

我做了一个函数,该函数从网站上抓取文本的最后64个字符,并将其添加url1,得到new_url。我想通过从结果URL(new_url)中抓取最后64个字符并将其再次添加url1中来重复此过程。我们的目标是重复此操作,直到我点击最后3个字符为“ END”的网站为止。

到目前为止,这是我的代码

#function
def getlink(url):
    url1 = 'https://www.uchicago.computer/api.PHP?file='
    req=request.urlopen(url)
    link = req.read().splitlines()

    for i,line in enumerate(link):
        text = line.decode('utf-8')
    
    last64= text[-64:]
    new_url= url1+last64
  
    return new_url



getlink('https://www.uchicago.computer/api.PHP?file=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz012345678910')
#output
'https://www.uchicago.computer/api.PHP?file=zyxwvutsrqponmlkjihgfedcba012345678910abcdefghijklmnopqrstuvwxyz'

我的麻烦是想办法在其输出上重复该功能。任何帮助将不胜感激!

解决方法

一个简单的循环应该起作用。我删除了第一个令牌,因为它可能是明智的信息。只需使用第一个链接的代码更改WRITE_YOUR_FIRST_TOKEN_HERE字符串即可。

from urllib import request


def get_chunk(chunk,url='https://www.uchicago.computer/api.php?file='):
    with request.urlopen(url + chunk) as f:
        return f.read().decode('UTF-8').strip()


if __name__ == '__main__':
    chunk = 'WRITE_YOUR_FIRST_TOKEN_HERE'
    while chunk[-3:] != "END":
        chunk = get_chunk(chunk[-64:])
        print(chunk)
        # Chunk is a string,do whatever you want with it,# like chunk.splitlines() to get a list of the lines

read获得字节流,decode将其转换为字符串,并且strip删除前导和尾随空格(例如\n),以免混乱最后64个字符(如果您得到最后64个字符,但其中一个是\n,则只会获得63个字符的令牌)。

,

尝试以下代码。它可以执行您上面提到的内容?

import requests
from bs4 import BeautifulSoup

def getlink(url):
    url1 = 'https://www.uchicago.computer/api.php?file='
    response = requests.post(url)
    doc = BeautifulSoup(response.text,'html.parser')
    text = doc.decode('utf-8')
    last64= text[-65:-1]
    new_url= url1+last64
  
    return new_url

def caller(url):
    url = getlink(url)
    if not url[-3:]=='END':
        print(url)
        caller(url)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。