[英]Repeat a python function on its own output
我做了一个 function 从网站上抓取文本的最后 64 个字符并将其添加到url1
,从而得到new_url
。 我想通过从生成的 URL ( new_url
) 中抓取最后 64 个字符并将其再次添加到url1
来重复该过程。 目标是重复此操作,直到我访问最后 3 个字符为“END”的网站。
到目前为止,这是我的代码:
#function
def getlink(url):
url1 = 'https://www.random.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.random/api.php?file=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz012345678910')
#output
'https://www.random/api.php?file=zyxwvutsrqponmlkjihgfedcba012345678910abcdefghijklmnopqrstuvwxyz'
我的麻烦是想办法在其 output 上重复 function。任何帮助将不胜感激!
一个简单的循环应该可以工作。 我删除了第一个标记,因为它可能是明智的信息。 只需将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
获取字节 stream, 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.