1. 程式人生 > >Python爬蟲——爬取網站的例項化原始碼

Python爬蟲——爬取網站的例項化原始碼

缺點:1爬了一個網站好幾次以後不能再進行爬取。沒有解決這個問題
      2在寫入資料的時候還是存在很大問題。以後多加練習這個檔案的儲存的相關工作
import re
import urllib.request

def function():
    """需求:1 https://read.douban.com/把所有的出版社的資訊提取出來 過濾掉無關資訊既可以
        2 儲存到本地檔案的資訊
    """
    #爬取得網站資訊
    html="http://read.douban.com/kind/505"
    data=urllib.request.urlopen(html).read()
    data=data.decode('utf-8')
    #爬取得正則表示式
    bookname='<a href="/ebook/\d*/">(.*?)</a>'#找到書名
    bookauthor='<a href="/author/\d*/" class="author-item">(.*?)</a>'#找到作者名字
    booktype='<span itemprop="genre">(.*?)</span>'#小說的型別
    #爬去的資訊資料
    bookname=re.compile(bookname).findall(data)
    bookauthor=re.compile(bookauthor).findall(data)
    booktype=re.compile(booktype).findall(data)
    #列印在控制檯
    print("bookname:",bookname)
    print("bookauthor",bookauthor)
    print("booktype",booktype)
    
    #將爬取的資料寫入檔案中
    txtName = "codingWord.txt"
    file = open('./作業二的資料.txt', "w",encoding="utf-8")
    file.write(str(bookname)+"\n"+str(bookauthor)+"\n"+str(booktype))
    file.close()
    file.close()
    return

if __name__ == '__main__':
    function()