天天看點

爬蟲綜合大作業

一.把爬取的内容儲存取MySQL資料庫

  • import pandas as pd
  • import pymysql
  • from sqlalchemy import create_engine
  • conInfo = "mysql+pymysql://user:passwd@host:port/gzccnews?charset=utf8"
  • engine = create_engine(conInfo,encoding='utf-8')
  • df = pd.DataFrame(allnews)
  • df.to_sql(name = ‘news', con = engine, if_exists = 'append', index = False)

二.爬蟲綜合大作業

  1. 選擇一個熱點或者你感興趣的主題。
  2. 選擇爬取的對象與範圍。
  3. 了解爬取對象的限制與限制。
  4. 爬取相應内容。
  5. 做資料分析與文本分析。
  6. 形成一篇文章,有說明、技術要點、有資料、有資料分析圖形化展示與說明、文本分析圖形化展示與說明。
  7. 文章公開釋出。

爬取汽車之家網站資訊:

1、主題:爬取汽車之家當中新聞的的内容,對内容中的詞語進行分析,生成詞雲

網址:https://www.autohome.com.cn/news/?p=s#liststart

2、具體步驟實作

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

/

/

擷取Url頁面中的時間、來源、名字和内容<br>

def

getNewsDetail(Url):

res 

=

requests.get(Url)

res.encoding 

=

'gb2312'

Ssoup 

=

BeautifulSoup(res.text, 

'html.parser'

)

news

=

{}

if

len

(Ssoup.select(

'.time'

))>

:

time 

=

Ssoup.select(

'.time'

)[

].text.rstrip(

' '

).lstrip(

'\r\n'

)

dt 

=

datetime.strptime(time, 

'%Y年%m月%d日 %H:%M'

)

else

:

dt

=

'none'

if

len

(Ssoup.select(

'.source'

))>

:

source 

=

Ssoup.select(

'.source'

)[

].text.lstrip(

"來源:"

)

else

:

source

=

'none'

if

len

(Ssoup.select(

'.name'

)) > 

:

name 

=

Ssoup.select(

'.name'

)[

].text.lstrip(

'\n'

).rstrip(

'\n'

)

else

:

name

=

'none'

if

len

(Ssoup.select(

'.details'

)) > 

:

content 

=

Ssoup.select(

'.details'

)[

].text.strip()

else

:

content 

=

'none'

news[

'time'

=

dt

news[

'source'

=

source

news[

'name'

=

name

news[

'content'

=

content

writeContent(news[

'content'

])

print

(dt,source,name,Url)

return

news

 由于是一個函數是以需要适應所有的頁面而不是隻是适合一個頁面,是以需要判斷是否存在時間、姓名、來源等,沒有的頁面給這些值賦予none

/

/

擷取一個頁面中有多少條新聞資訊<br>

def

getListPage(pageUrl):

res 

=

requests.get(pageUrl)

res.encoding 

=

'gb2312'

soup 

=

BeautifulSoup(res.text, 

'html.parser'

)

newslist 

=

[]

for

in

soup.select(

".article-wrapper"

):

for

in

a.select(

'li'

):

if

len

(b.select(

"a"

)) > 

:

newsUrl 

=

'http:'

+

b.select(

"a"

)[

].attrs[

'href'

]

newslist.append(getNewsDetail(newsUrl))

return

(newslist)

 由于該頁面中存在許多li,是以需要對li和a先進行便利

/

/

擷取有多少頁<br>

def

getPageN():

res 

=

requests.get(pageUrl)

res.encoding 

=

'gb2312'

soup 

=

BeautifulSoup(res.text, 

'html.parser'

)

for

in

soup.select(

'.page'

):

=

int

(a.select(

'a'

)[

10

].text)

return

n

  

pageUrl

=

'https://www.autohome.com.cn/news/'

newstotal 

=

[]

newstotal.extend(getListPage(pageUrl))

=

getPageN()

for

in

range

(

2

,n):

listPageUrl 

=

'https://www.autohome.com.cn/news/{}/#liststart'

.

format

(i)

newstotal.extend(getListPage(listPageUrl))

# df = pandas.DataFrame(newstotal)
# import openpyxl
# df.to_excel('work.xlsx')      

由于該新聞網站的頁面過多,在爬取過程胡出現連接配接錯誤,是以在後面的内容隻是爬取到第161頁的資料,大概2018年一整年的資料

/

/

将<br>

import

jieba

=

open

(

'content.txt'

,

'r'

,encoding 

=

'utf-8'

)

story

=

f.read()

f.close()

sep

=

''',。‘’“”:;()!?、《》 . < > / - 0 1 2 3 4 5 6 7 8 9

A B C D E F G H I J K L M N O P Q R S T U V W X Y J

a b c d e f g h i j k l m n o p q r s t u v w x y j'''

exclude

=

{

' '

,

' '

,

' '

}

for

in

sep:

story 

=

story.replace(c,'')

tem

=

list

(jieba.cut(story))

wordDict

=

{}

words

=

list

(

set

(tem)

-

exclude)

for

in

range

(

,

len

(words)):

wordDict[words[w]]

=

story.count(

str

(words[w]))

dictList 

=

list

(wordDict.items())

dictList.sort(key

=

lambda

x:x[

1

],reverse

=

True

)

=

open

(

'news.txt'

'a'

,encoding

=

"utf-8"

)

for

in

range

(

150

):

f.write(dictList[i][

]

+

'\n'

)

f.close()

 讀取剛剛爬取的content.txt中的内容,用jieba詞庫對内容進行分詞,統計前150個祠是什麼,然後存儲到news.txt中 

import

wordcloud

from

PIL 

import

Image,ImageSequence

import

numpy as np

import

matplotlib.pyplot as plt

from

wordcloud 

import

WordCloud,ImageColorGenerator

import

jieba

=

open

(

"news.txt"

,

"r"

,encoding

=

'utf-8'

)

str1 

=

f.read()

stringList 

=

list

(jieba.cut(str1))

delset 

=

{

","

,

"。"

,

":"

,

"“"

,

"”"

,

"?"

,

" "

,

";"

,

"!"

,

"、"

}

stringset 

=

set

(stringList) 

-

delset

countdict 

=

{}

for

in

stringset:

countdict[i] 

=

stringList.count(i)

image

=

Image.

open

(

'G:\Work\Python1\\789.jpg'

)

graph 

=

np.array(image)

font

=

r

'C:\Windows\Fonts\simhei.TTF'

wc 

=

WordCloud(font_path

=

font,background_color

=

'White'

,max_words

=

100

,mask

=

graph)

wc.generate_from_frequencies(countdict)

image_color 

=

ImageColorGenerator(graph)

plt.imshow(wc)

plt.axis(

"off"

)

plt.show()

讀取news.txt中擷取的前150個祠,生成詞雲

3、結果

爬蟲綜合大作業
爬蟲綜合大作業
爬蟲綜合大作業
爬蟲綜合大作業
爬蟲綜合大作業

 4、思想及結論

爬蟲爬取資料還是具有一定的實際意義,從汽車之家的新聞網站中可以擷取到汽車新聞資訊的熱門詞彙,增長對汽車的了解。

通過這次的爬蟲大作業,加深我對爬取資料步驟等的了解和運用,在以後的工作生活中會起到一定作用。