1. 程式人生 > >Python爬蟲爬取CSDND首頁的所有的文章

Python爬蟲爬取CSDND首頁的所有的文章

 

# -*- encoding: utf-8 -*-

import re
import urllib.request

def function():
    """Python爬蟲爬取CSDND首頁的所有的文章"""
    html="https://blog.csdn.net/nav/engineering"
    #模擬瀏覽器
    headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/63.0")#這裡用的是Fix瀏覽器進行爬取的一個報頭如果是採用其他的這個報頭就要進行更換
    opener=urllib.request.build_opener()
    opener.addheader=[headers]
    urllib.request.install_opener(opener)

    data = urllib.request.urlopen(html).read()
    data = data.decode("utf-8", "ignore")
    print(data)
    pattern='<h3 class="company_name"><a href="(.*?)"'
    mydata=re.compile(pattern).findall(data)
    print(mydata)
    for i in range(0,len(mydata)):
        file="E:/資料探勘練習/網頁/"+str(i)+".html"
        urllib.request.urlretrieve(mydata[i],filename=file)
        print("第%d次爬取成功"%i)

    print("CSDN爬蟲結束")

if __name__ == '__main__':
    function()