问题描述
我做了一个函数,该函数从网站上抓取文本的最后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)