【爬虫】(二)windows10download.com

2,922 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

⭐ 爬虫系列文章旨在记录一些与网络爬虫相关的内容(在合法合规的情况下),并结合实战,让读者能够更快更深地理解与掌握。

🔥 本文已收录于爬虫系列专栏: 爬虫专栏 欢迎订阅,持续更新。

🎉 欢迎关注👀 点赞👍 收藏⭐ 留言📝

💬 代码成就万世基,积沙镇海;梦想永在凌云意,意气风发; 𝓼𝓲𝓭𝓲𝓸𝓽

前言

因为毕设是基于机器学习的,所以需要大量的样本来训练模型和检验成果,因此,通过爬虫,在合法合规的情况下,爬取自己所需要的资源,在此进行记录;

本次爬取的网站是 www.windows10download.com/

总的代码都会在 运行 中贴出...

再次申明:本博文仅供学习使用,请勿他用!!!  

成果

image.png

image.png

 

观察

页面还是比较简洁的,可以直接按目录分类来进行之后的操作;

image.png

选取目录之后,随机抽取几个软件,进入详情页观察一下情况,

image.png

可以看到,红框处就是该软件的下载地址了,通过点击就能直接下载文件了;

image.png

 

分析

大致浏览之后,接下来就是进行分析以及分步操作了;

1、先请求一下网页,看看是否能请求成功;

2、接下来先获取一个分类类别下的页数,

# 获取页数
obj = re.compile(r"<li> \([0-9]+.*?pages\)</li>", re.S)
res = obj.finditer(resp.text)
for it in res:
    page_size = it.group().split('(')[-1].split('&')[0]
    break

image.png

 

3、获取每个软件的详情页的 URL,

# 获取当前页的每个软件的 url
obj = re.compile(r'[a-zA-z]+://[^\s]*/download.html', re.S)
res = obj.finditer(requests.get(url, proxies=proxies).text)
detail_urls = [it.group() for it in res]

4、进入下载详情页之后,就要开始获取下载链接了,但是由于各种因素,会导致下载链接失效,因此要先进行判断该链接是否有效,

def get_effective_url(url):
    # url = 'https://www.windows10download.com/thundersoft-gemplayer/download.html'
    obj = re.compile(r'http(|s)%253A%252F%252[^\s]*" rel="nofollow"', re.S)
    res = obj.finditer(requests.get(url, proxies=proxies).text)
    hrefs = [it.group().split('"')[0] for it in res]
    effective_urls = {}
    for href in hrefs:
        new_url = f"https://www.windows10download.com/rd.html?url={href}"
        response = requests.get(new_url, stream=True, timeout=30, proxies=proxies)
        # 判断是否为可下载文件
        if 'Content-Length' in response.headers.keys():
            effective_urls["name"] = url.split('/')[-2]+".zip"
            effective_urls["url"] = new_url
            break
    return effective_urls

# {'name': 'thundersoft-gemplayer.zip', 'url': 'https://www.windows10download.com/rd.html?url=https%253A%252F%252Fwww.thundershare.net%252Fdownload%252Fgemplayer.zip&h=9e8f0f32dd50438bd9db0d1198dc2cfb'}

5、将上述的操作进行合并,变成一个一步到位获取到下载地址的函数:

def get_download_url(url):
    name = []
    urls = []
    d_urls = get_detail_urls(url)
    for o_url in d_urls:
        try:
            info = get_effective_url(o_url)
            if info != {}:
                name.append(info["name"])
                urls.append(info["url"])
        except:
            pass

    return name, urls

image.png

6、既然获取到了地址,那就可以开始下载了,为了方便多线程的运行,可以先写一个下载函数,

def download_zip(url, name):
    try:
        filepath = os.path.join(os.getcwd(), name)
        cc = 0
        start = time.time()
        while cc < 5:
            try:
                path, headers = urllib.request.urlretrieve(url, filepath)
                print()
                break

            except socket.timeout:
                cc += 1
                if (cc == 5): 
                    print(name, "ConnectionError --> END!\n")
                    raise Exception('4016 NETWORK TERRIBLE!')
                print(name, "ConnectionError", cc)
                time.sleep(30*cc)
            
        pe_size = int(headers['content-length']) / 1024 / 1024
        end = time.time()
        print(
            f'本地路径: \"{path}\" --> {pe_size:.2f} MB--> 用时 {(end - start):.2f} 秒 --> {url}')
        return True

    except urllib.error.ContentTooShortError as e:
        print(name + " ContentTooShortError: " + e.reason)

    except urllib.error.URLError:
        pass

    except Exception as e:
        print(e)
        print(f"收集失败  --> {url}")

 

7、加入多线程就可以了;

 

运行

这板块现在有版权风险,不能贴全部的代码,点这里;  

后记

仅仅用来记录毕设期间所爬过的网站;

再次申明:本博文仅供学习使用,请勿他用!!!

📝 上篇精讲:【爬虫】(一)fossies.org

💖 我是 𝓼𝓲𝓭𝓲𝓸𝓽,期待你的关注;

👍 创作不易,请多多支持;

🔥 系列专栏: 爬虫专栏