天天看點

爬蟲綜合大作業

作業要求來源于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/3075

一.把爬取的内容儲存取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. 文章公開釋出。

參考:

32個Python爬蟲項目

都是誰在反對996?

Python和Java薪資最高,C#最低!

給《流浪地球》評1星的都是什麼心态?

《都挺好》彈幕資料,比劇情還精彩?

爬了自己的微信好友,原來他們是這樣的人……

春節人口遷徙大資料報告!

七夕前消費趨勢資料

爬了一下天貓上的Bra購買記錄,有了一些羞羞哒的發現...

Python做了六百萬字的歌詞分析,告訴你中國Rapper都在唱些啥

分析了42萬字歌詞後,終于搞清楚民謠歌手唱什麼了

十二星座的真實面目

唐朝詩人之間的關系到底是什麼樣的?

中國姓氏排行榜

三.爬蟲注意事項

1.設定合理的爬取間隔,不會給對方運維人員造成壓力,也可以防止程式被迫中止。

  • import time
  • import random
  • time.sleep(random.random()*3)

2.設定合理的user-agent,模拟成真實的浏覽器去提取内容。

  1. 首先打開你的浏覽器輸入:about:version。
  2. 使用者代理:
  3. 收集一些比較常用的浏覽器的user-agent放到清單裡面。
  4. 然後import random,使用随機擷取一個user-agent
  5. 定義請求頭字典headers={’User-Agen‘:}
  6. 發送request.get時,帶上自定義了User-Agen的headers

3.需要登入

發送request.get時,帶上自定義了Cookie的headers

headers={’User-Agen‘:  

'Cookie':    }

4.使用代理IP

通過更換IP來達到不斷高 效爬取資料的目的。

headers = {
    "User-Agent": "",
}
proxies = {
    "http": " ",
    "https": " ",
}
response = requests.get(url, headers=headers, proxies=proxies)      

四、爬取豆瓣的影評

爬取《流浪地球》的好、中、差短評并分詞分析。

爬蟲綜合大作業
爬蟲綜合大作業
爬蟲綜合大作業
import os
import requests
import codecs
from bs4 import BeautifulSoup

# 給請求指定一個請求頭來模拟chrome浏覽器
global headers
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'}
server = 'https://movie.douban.com/subject/26266893/comments'
# 定義存儲位置
global save_path
save_path = os.getcwd()+"\\Text\\"+'短評_差評.txt'
global page_max
page_max = 25
global comments
comments = ''


# 擷取短評内容

def get_comments(page):

    req = requests.get(url=page)
    html = req.content
    html_doc = str(html, 'utf-8')
    bf = BeautifulSoup(html_doc, 'html.parser')
    comment = bf.find_all(class_="short")
    for short in comment:
        global comments
        comments = comments + short.text

# 寫入檔案
def write_txt(chapter, content, code):
    with codecs.open(chapter, 'a', encoding=code)as f:
        f.write(content)

# 主方法
def main():
    for i in range(0, page_max):
        try:
            page = server + '?start='+str(i*20)+'&limit=20&sort=new_score&status=P&percent_type=1'
            get_comments(page)
            write_txt(save_path, comments, 'utf8')
        except Exception as e:

            print(e)

if __name__ == '__main__':
    main()      

爬取内容

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

以下為各類高頻詞分析

# -*- coding: utf-8 -*-
"""

@author: Rozmin
"""

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba

txt = open(r'短評_差評.txt', 'r', encoding='utf-8').read()
s = [line.strip() for line in open('CIyun.txt', encoding='utf-8').readlines()]
jieba.load_userdict(s)
wordcut = jieba.lcut(txt)
wdict = {}
for word in wordcut:
    if word not in s:
        if len(word) == 1:
            continue
        else:
            wdict[word] = wdict.get(word, 0) + 1
wc = list(wdict.items())
wc.sort(key=lambda x: x[1], reverse=True)
for i in range(25):
    print(wc[i])
cut_text = " ".join(wordcut)
'print(cut_text)'
mywc = WordCloud(font_path='msyh.ttc').generate(cut_text)
plt.imshow(mywc)
plt.axis("off")
plt.show()      

抓取高頻詞前30

import jieba
import os

txt = open(os.getcwd()+"\\Text\\"+"短評_好評.txt","r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}

for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word, 0) + 1

items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)

for i in range(0, 1):
    word, count = items[i]
print("{0:<6}{1:>6}".format(word, count))      

好評的高頻詞分析:

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

 中評的高頻詞分析:

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

差評的高頻詞分析:

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

前十好評高頻出現詞彙:

前十中評高頻出現詞彙:

前十差評高頻出現詞彙:

前十高頻詞彙分析基本沒有任何參考價值,基本就是科幻、地球、特效、電影,這些都是電影的基本元素,其它的都是一些中性詞彙。

然後,分析了11-30的高頻詞彙,提取了部分關鍵詞:

好評:

中評:

差評:

總結

同類評分電影中,小破球的一星占比出奇的高。不管是意識形态還是商業利益,《流浪地球》注定要被美分狗和《戰狼》PTSD 患者往死裡整。《流浪地球》的評價問題已經不僅僅是一部電影的問題。《流浪地球》的口碑一度遭遇了嚴重下滑,更有人在豆瓣評分上惡意刷評價、改評價,導緻電影評分從最初的高分8.5一下狂跌至7.9分。