下载直接下载到指定文件夹



我有这个代码,我使用beautifulsoup获得一个直接下载链接到pdf的url,并将其保存到特定的目录。

获取链接的url有效,它只是让它下载并保存在导致问题的目录中。我搜索了几个资源,最后尝试了urllib。

请帮我一下好吗?编辑:我想做的主要事情是让代码下载直接链接,而不必手动点击它。

如果url需要帮助,它在这里;https://www.odfl.com/us/en/resources/tariffs/tariff-odfl-100-0.html我是通过一个xml解析,如还有其他几个url需要不同的代码。

import sys
import os
import re
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import urllib
import xml.etree.ElementTree as ET
def ODFL100(tariff_id):
try:
pdf_path = ParseXML(tariff_id)
r = requests.get(pdf_path,stream = True)
download_path = ParseXML(tariff_id,1)
link_list = []
pdf_link = ""
pdf_found = 0
r = requests.get(pdf_path)
soup = BeautifulSoup(r.text, "html.parser")
base = urlparse(pdf_path)
for i in soup.find_all('a'):
if pdf_found == 0:
current_link = i.get('href')
else:
break
if current_link.endswith('pdf'):
link_list.append(base.scheme+"://"+base.netloc + current_link)
for l in link_list:
pdf_link = l
if "rates-and-tariffs"  in pdf_link:
pdf_found = 1
urllib.urlretrieve(pdf_link, download_path)
except Exception as error:
error_message = "A " + str(error)

我不太明白你想达到什么目的。但这里有一个示例代码,将从指定页面下载pdf文件。

import requests
from bs4 import BeautifulSoup

url = 'https://www.odfl.com/us/en/resources/tariffs/tariff-odfl-100-0.html'
response = requests.get(url)
link = 'https://www.odfl.com' + BeautifulSoup(response.text, 'lxml').find('a', class_='cmp-form-button').get('href')
with open(requests.utils.unquote((link.split('/')[-1])), 'wb') as f:
f.write(requests.get(link).content)

最新更新