我整整为此苦苦挣扎。我编译通过在网页上使用urllib3(也使用BeautifulSoup)获得的URL列表。这些URL基本上指向我要自动下载的pdf文件。很棒的是pdf链接具有漂亮的图案。因此,我可以轻松地使用正则表达式制作要下载的pdf列表,而忽略其余部分。但这就是问题的出处。 URL遵循http://www.ti.com/lit/sboa263模式
注意:最后一部分更改为其他文件,没有pdf文件扩展名。
但是,如果将此链接放在浏览器中,则可以清楚地看到它从http://www.ti.com/general/docs/lit/getliterature.tsp?baseLiteratureNumber=sboa263更改为http://www.ti.com/lit/an/sboa263/sboa263.pdf,并最终更改为
现在,我了解到您可以告诉我“太好了,那就遵循这种模式”。但是我不想因为IMO,这不是解决这种自动化问题的正确方法。我希望能够从第一个链接本身下载pdf。
我已经尝试过
response = requests.get(url,allow_redirects=True)
,它只能将我带到第一个重定向的结果,而不是最后一个文件的结果。甚至
response.history
也只能将我带到第一个重定向。而且当我无论如何尝试下载文件时,我得到了无法打开的损坏的pdf。但是,当我手动传递最终URL只是为了测试文件写入的正确性时,我会以完美的顺序获得实际的pdf。
我不明白为什么请求无法到达最终URL。
我的完整代码如下,以供您参考-
from bs4 import BeautifulSoup
import urllib3
import re
http = urllib3.PoolManager()
url = 'http://www.ti.com/analog-circuit/circuit-cookbook.html'
response = http.request('GET', url)
soup = BeautifulSoup(response.data)
find = re.compile("http://www.ti.com/lit/")
download_links = []
for link in soup.find_all('a'):
match = re.match(find, link.get('href'))
if match:
#print(link.get('href'))
download_links.append(link.get('href'))
要使用重定向的网址,我使用-
import requests
response = requests.get(download_links[45])
if response.history:
print ("Request was redirected")
for resp in response.history:
final_url = resp.url
response = requests.get(final_url)
为了下载文件,我使用了以下代码-
with open('C:/Users/Dell/Desktop/test.pdf', 'wb') as f:
f.write(response.content)
我实际上也只是想传递一个文件夹名称,所有文件都应使用URL本身最后一部分的名称下载。我还没有弄清楚该怎么做。我试过shuttles,但是没有用。如果您也可以在那部分帮助我,那就太好了。
编辑:我将前两个URL传递给Postman,而我得到了HTML,而传递第三个URL则下载了pdf。在获得的HTML中,我可以清楚地看到Meta属性之一列出了最终的pdf URL。这是有关邮递员结果的一部分-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta content="IE=8;IE=9;IE=edge" http-equiv="x-ua-compatible">
<meta content='width=device-width, initial-scale=1.0' name='viewport'>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<META HTTP-EQUIV="Refresh" CONTENT="1; URL=http://www.ti.com/lit/an/sboa263/sboa263.pdf">
以下各部分还显示了最终URL,但我认为您可以理解。我们可以利用这些信息吗?
最佳答案
如Miraj50所述,确实是将其带到最终URL的元刷新。因此,我从meta标记中提取了最终的url,并能够下载所有45个pdf。以下是相同的代码-
for links in download_links[5:]:
response = requests.get(links)
if response.history:
print ("Request was redirected")
print(response.url)
r = response.url
从元标记获取链接-
# The redirected url then uses meta refresh
meta_response = http.request('GET', r)
meta_soup = BeautifulSoup(meta_response.data)
meta_result = meta_soup.find('meta',attrs={'http-equiv':'Refresh'})
#print(meta_result)
wait,text = meta_result["content"].split(";")
final_url = text.strip()[4:]