Python爬虫实战,requests模块,Python多线程抓取5千多部最新电影下载链接

前言

利用Python多线程爬了5000多部最新电影下载链接,废话不多说~

让我们愉快地开始吧~

开发工具

Python版本: 3.6.4

相关模块:

requests模块;

re模块;

csv模块;

以及一些Python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

1.png

bs = BeautifulSoup(html, "html.parser")
b = bs.findAll(class_="co_content8")
b = b[0].findAll(class_="ulink")

拿到链接之后,接下来就是继续访问这些链接,然后拿到电影的下载链接

2.png

bs1 = BeautifulSoup(html1, "html.parser")
b1 = bs1.find("tbody").find_next("td").find_next("a")
download_url = b1.get("href")

但是这里还是有很多的小细节,例如我们需要拿到电影的总页数,其次这么多的页面,一个线程不知道要跑到什么时候,所以我们首先先拿到总页码,然后用多线程来进行任务的分配

我们首先先拿到总页码,然后用多线程来进行任务的分配

3.png

总页数其实我们用re正则来获取

def get_total_page(url):
    r = requests.get(url=url,headers=headers)
    r.encoding = 'gb2312'
    pattern = re.compile(r'(?<=页/)\d+')
    t = pattern.findall(r.text)
    return int(t[0])

爬取的内容存取到csv,也可以写个函数来存取

def wirte_into_csv(name,down_url):
    f = open('最新电影.csv', 'a+', encoding='utf-8')
    csv_writer = csv.writer(f)
    csv_writer.writerow([name,down_url])
    f.close()

本文源码滴我666

开启4个进程来下载链接

total_page = get_total_page("https://www.ygdy8.com/html/gndy/oumei/list_7_1.html")
    total_page = int(total_page/25+1)
    end = int(total_page/4)
    try:
        _thread.start_new_thread(run, (1, end))
        _thread.start_new_thread(run, (end+1, end*2))
        _thread.start_new_thread(run, (end*2 + 1, end * 3))
        _thread.start_new_thread(run, (end*3 + 1, end * 4))
    except:
        print("Error: 无法启动线程")

    while(1):
        pass

4.png

5.png

猜你喜欢

转载自blog.csdn.net/weixin_43649691/article/details/122186721