找到所有需要下载的链接
links = []
for link in soup.find_all('a'):
href = link.get('href')
if href and href.endswith('.pdf'): 假设你要下载PDF文件
links.append(href)
创建保存目录
os.makedirs('downloads', exist_ok=True)
下载文件
for i, link in enumerate(links):
file_url = fhttps://65.hk{link} 根据实际情况调整URL
file_name = os.path.join('downloads', f'document_{i}.pdf')
with open(file_name, 'wb') as f:
f.write(requests.get(file_url).content)
print(fDownloaded {file_name})
4、使用爬虫框架
如果数据结构复杂或需要处理动态加载的内容,可以使用爬虫框架,如Scrapy。
示例代码(使用Scrapy):
python
import scrapy
class DataSpider(scrapy.Spider):
name = data_spider
start_urls = [https://65.hk/data]
def parse(self, response):
for link in response.css('a[href$=.pdf]::attr(href)').getall():
yield response.follow(link, callback=self.save_file)
def save_file(self, response):
file_path = 'downloads/' + response.url.split('/')[1]
self.logger.info(f'Saving PDF file to {file_path}')
with open(file_path, 'wb') as f:
f.write(response.body)
运行爬虫:
bash
scrapy crawl data_spider
5、使用wget或curl
如果网页上的文件可以通过直接访问链接下载,可以使用命令行工具批量下载。
wget 示例:
bash
wget r np A.pdf http://65.hk/data/
参数说明:
`r`:递归下载
`np`:不向上级目录下载
`A.pdf`:只下载`.pdf`文件
curl 示例:
如果你知道所有文件的链接列表,可以直接用`curl`下载:
bash
curl O http://65.hk/file1.pdf
curl O http://65.hk/file2.pdf