使用python下载文件-PDF

本文介绍了一个使用Python实现的网页爬虫项目,该项目通过requests和BeautifulSoup库抓取指定网站上的链接,并利用多线程技术同时下载多个PDF文件。文章详细展示了如何设置请求头、解析网页内容、提取链接以及使用线程池进行高效下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
from bs4 import BeautifulSoup
import threading
import time
import urllib.request


url = 'http://www.mee.gov.cn/hjzl/dqhj/cskqzlzkyb/'
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
class DouYinMusic:

    def __init__(self):
        self.download_path()

    @staticmethod#静态方法
    def download_path(self=None):
        global url
        global headers
        r = requests.get(url,headers=headers)
        r.encoding = 'UTF-8'
        soup = BeautifulSoup(r.text, 'html.parser')
        for tag_div in soup.findAll(True, {'class': 'main_rt_list'}):
            for tag_a in tag_div.find_all('a'):
                print('tag_a', tag_a.get('href')[2:])
                print('tag_a', tag_a.text)
                t = threading.Thread(target=self.download_pdf, args=(tag_a))
                time.sleep(0.5)
                t.start()



def download_pdf(tag_a):
    u = urllib.request.urlopen(url + tag_a.get('href')[2:])
    f = open('C://Users//m//Desktop//down//' + tag_a.text + '.pdf', 'wb')
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break
        print('=====结束==========')
        f.write(buffer)
    f.close()


if __name__ == '__main__':
    main = DouYinMusic()
    #main.run()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值