1. 程式人生 > >學習了一個月python,進行實戰一下:爬取文章標題和正文並儲存的程式碼

學習了一個月python,進行實戰一下:爬取文章標題和正文並儲存的程式碼

爬取東方財富網文章標題和正文並儲存的程式碼。自己知道寫的很爛,不過主要是為了自己備忘,也為了以後回頭看看自己的爛作品,哈哈哈。

#!/usr/bin/env python
# -*- coding:utf-8 -*-


import requests
from bs4 import BeautifulSoup
import time

#實現根據url進行網頁爬取,並得到想要的文字資訊,儲存在一個檔案列表txtlist中。
def gethtml(url,deep,txtlist):

    try:
        for i in range(deep):
            print('>>>>>',deep-i)
            r = requests.get(url + str(i + 1), timeout=30)
            if r.status_code == 200:
                r.encoding = r.apparent_encoding
                r.raise_for_status()

                soup = BeautifulSoup(r.text,'html.parser')
                a = soup.find_all('p',class_='title')
                for b in a:
                    c = b.find_all('a')

                    print(c[0].text,c[0]['href'])
                    #將爬取的文章標題和正文連結新增進txtlist變數中
                    txtlist.append('>>>>>>>'+c[0].text+c[0]['href']+'\n')
                    #通過request將正文連結進入正文,爬取正文。
                    r1 = requests.get(c[0]['href'], timeout=30)
                    r1.raise_for_status()
                    r1.encoding = r1.apparent_encoding

                    soup1 = BeautifulSoup(r1.text, 'html.parser')
                    a1 = soup1.find_all('div', id='ContentBody')
                    # print(a)
                    for b1 in a1:
                        c1 = b1.find_all('p')
                        for e1 in c1:
                            print(e1.text)
                            #將每篇的正文再次賦予txtlist變數
                            txtlist.append(e1.text)



            i += 1
    except:
        print('有錯誤發生')
        return

#將txtlist列表中的資料儲存到E盤111.txt檔案中。
def savefile(txt):
    try:
        with open('e:111.txt', 'a', encoding='utf-8') as f:
            timenow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            print(timenow)
            f.write('>>文章爬取時間>>' + timenow + '>>>>>>>' + txt + '\n')
    except:
        print('有錯誤未能存檔')
    return

#呼叫的主函式
def main():
    deep = 2 #定義要抓取多少層頁面
    url = 'http://finance.eastmoney.com/news/cdfsd.html'
    txtlist = []
    gethtml(url,deep,txtlist)
    txt = ''.join(txtlist) #將列表檔案變成字串檔案,便於進行儲存。
    print(txt)
    savefile(txt)
main()