我试图在python代码中获取一个字符串输入,将其转换并实现为一个URL,以便在网站上搜索该字符串。我使用的网站是songbpm.com网站我想要的是搜索一首歌,然后我得到这首歌的速度。在HTML中查找相关信息不是问题,我已经完成了这项工作,我的url创建工作正在进行,如下所示:
import urllib.request
import urllib.parse
song = input("")
fin = ""
for i in song:
if i == "(":
tempone = song
song = tempone.split("(")[0] + tempone.split(") ")[1]
previous = ""
for i in song:
if i.isalpha():
temp = fin
fin = temp + i
else:
if previous.isalpha():
temp = fin
fin = temp + "-"
previous = i
songencoded = urllib.parse.quote(song, safe='')
print('https://songbpm.com/'+ fin.lower() + '?q=' + songencoded)
response = urllib.request.urlopen('https://songbpm.com/'+ fin.lower() + '?q=' + songencoded)
text = str(response.read()).split('\\n')
返回的url与我在网站上手动输入搜索输入时的url相同,但是,当我运行此代码时,它总是读取no results重定向的html数据。你知道吗
另外,如果我将计算机生成的URL粘贴到浏览器中,它会重定向到“无结果”页,但是,在浏览器中手动搜索同一字符串后,计算机生成的URL也会起作用(重试时)。你知道吗
我还观察到,在手动打开某个URL之后,我可以使用相同的搜索查询运行代码,并且它可以工作—如果用户(而不是代码)打开某个URL,搜索似乎会被缓存一段时间。你知道吗
我如何处理这个问题的代码,虽然生成确切的网址,不能打开网页类似的用户。你知道吗
好吧,我不知道是什么样的魔力在驱动这个网站,但你可以使用无头浏览器,而不是在url中寻找歌曲,你可以在搜索框中键入你正在寻找的歌曲的名称,它会起作用!对不起,我没答对你的问题
这里有一个100%的工作代码:)玩得开心
该网站有一些额外的要求,使适当的要求。首先它使用cookies,所以需要一个^{} 。这可以通过首先请求主页而不进行搜索来加载。然后,这也为您提供了提交请求表单时所需的} 正确构建
_csrf
值。最后,通过使用^{q
,可以从输入搜索生成POST请求:这将给你以下结果:
使用
beautifulsoup
可以很容易地提取所有细节。itemgetter()
只是从给定列表中快速获取某些项的一种方法。你知道吗相关问题 更多 >
编程相关推荐