Python爬蟲實戰,requests模塊,Python多線程抓取5千多部最新電影下載鏈接 前言 開發工具 環境搭建

前言

利用Python多線程爬了5000多部最新電影下載鏈接,廢話不多說~

讓我們愉快地開始吧~

開發工具

Python版本: 3.6.4

相關模塊:

requests模塊;

re模塊;

csv模塊;

以及一些Python自帶的模塊。

環境搭建

安裝Python並添加到環境變量,pip安裝需要的相關模塊即可。

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

拿到鏈接之後,接下來就是繼續訪問這些鏈接,然後拿到電影的下載鏈接

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

但是這裏還是有很多的小細節,例如我們需要拿到電影的總頁數,其次這麼多的頁面,一個線程不知道要跑到什麼時候,所以我們首先先拿到總頁碼,然後用多線程來進行任務的分配

我們首先先拿到總頁碼,然後用多線程來進行任務的分配

總頁數其實我們用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()

開啓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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章