爬蟲大做業

 

2.用python 編寫爬蟲程序,從網絡上爬取相關主題的數據。app

(1)環境配置:dom

import requests  ##導入requests
from bs4 import BeautifulSoup  ##導入bs4中的BeautifulSoup
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'}
all_url ='http://heyuan.8684.cn/' ##開始的URL地址
start_html = requests.get(all_url, headers=headers)
#print(start_html.text)
Soup = BeautifulSoup(start_html.text, 'html.parser') 

(2)爬取站點分析:函數

a、河源市公交線路分類方式有3種:網站

b、我主要經過數字開頭來進行爬取,打開網站,點擊「1」,右擊鼠標選擇「檢查」,能夠發現保存在連接保存在<div class="bus_kt_r1">裏面,故只須要提取div裏的href便可:url

代碼:spa

all_1 = Soup.find('div', class_='bus_kt_r1').find_all('a')#獲取以數字開頭全部路線

c、接着往下,發現每一路的連接都在<div id="con_site_1" class="site_list"> <a>裏面,取出裏面的herf即爲線路網址,其內容即爲線路名稱。code

代碼:

href = a['href']  # 取出a標籤的href 屬性
html = all_url + href
second_html = requests.get(html, headers=headers)
#print(second_html.text)
Soup2 = BeautifulSoup(second_html.text, 'html.parser')
all_a2 = Soup2.find('div', class_='stie_list').find_all('a')

 

 d、打開線路連接,就能夠看到具體的站點信息了,打開頁面分析文檔結構後發現:線路的基本信息存放在<div class="bus_i_content">裏面,而公交站點信息則存放在<div class="bus_line_top"><div class="bus_line_site">裏面。

提取代碼:

title1 = a2.get_text()  # 取出a1標籤的文本
        href1 = a2['href']  # 取出a標籤的href 屬性
   # print(title1, href1)
        html_bus = all_url + href1  # 構建線路站點url
        thrid_html = requests.get(html_bus, headers=headers)
        Soup3 = BeautifulSoup(thrid_html.text, 'html.parser')  # 以html.parser方式解析html
        bus_name = Soup3.find('div', class_='bus_i_t1').find('h1').get_text()  # 提取線路名
        bus_type = Soup3.find('div', class_='bus_i_t1').find('a').get_text()  # 提取線路屬性
        bus_time = Soup3.find_all('p', class_='bus_i_t4')[0].get_text()  # 運行時間
        bus_cost = Soup3.find_all('p', class_='bus_i_t4')[1].get_text()  # 票價
        bus_company = Soup3.find_all('p', class_='bus_i_t4')[2].find('a').get_text()  # 公交公司
        bus_update = Soup3.find_all('p', class_='bus_i_t4')[3].get_text()  # 更新時間
        bus_label = Soup3.find('div', class_='bus_label')
        if bus_label:
            bus_length = bus_label.get_text()  # 線路里程
        else:
            bus_length = []
        print(bus_name, bus_type, bus_time, bus_cost, bus_company, bus_update)
        all_line = Soup3.find_all('div', class_='bus_line_top')  # 線路簡介
        all_site = Soup3.find_all('div', class_='bus_line_site')  # 公交站點
        line_x = all_line[0].find('div', class_='bus_line_txt').get_text()[:-9] + all_line[0].find_all('span')[
            -1].get_text()
        sites_x = all_site[0].find_all('a')
        sites_x_list = []  # 上行線路站點
        for site_x in sites_x:
            sites_x_list.append(site_x.get_text())
        line_num = len(all_line)
        if line_num == 2:  # 若是存在環線,也返回兩個list,只是其中一個爲空
            line_y = all_line[1].find('div', class_='bus_line_txt').get_text()[:-9] + all_line[1].find_all('span')[
                -1].get_text()
            sites_y = all_site[1].find_all('a')
            sites_y_list = []  # 下行線路站點
            for site_y in sites_y:
                sites_y_list.append(site_y.get_text())
        else:
            line_y, sites_y_list = [], []
        information = [bus_name, bus_type, bus_time, bus_cost, bus_company, bus_update, bus_length, line_x, sites_x_list,
                       line_y, sites_y_list] 

e、自此,咱們就把一條線路的相關信息及上、下行站點信息就都解析出來了。若是想要爬取全市的公交網絡站點,只須要加入循環就能夠了。

代碼:

import requests  ##導入requests
from bs4 import BeautifulSoup  ##導入bs4中的BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'}
all_url ='http://heyuan.8684.cn/' ##開始的URL地址
start_html = requests.get(all_url, headers=headers)
#print(start_html.text)
Soup = BeautifulSoup(start_html.text, 'html.parser')
all_1 = Soup.find('div', class_='bus_kt_r1').find_all('a')#獲取以數字開頭全部路線
Network_list = []
for a in all_1:
    href = a['href']  # 取出a標籤的href 屬性
    html = all_url + href
    second_html = requests.get(html, headers=headers)
    #print(second_html.text)
    Soup2 = BeautifulSoup(second_html.text, 'html.parser')
    all_a2 = Soup2.find('div', class_='stie_list').find_all('a')
    for a2 in all_a2:
        title1 = a2.get_text()  # 取出a1標籤的文本
        href1 = a2['href']  # 取出a標籤的href 屬性
   # print(title1, href1)
        html_bus = all_url + href1  # 構建線路站點url
        thrid_html = requests.get(html_bus, headers=headers)
        Soup3 = BeautifulSoup(thrid_html.text, 'html.parser')  # 以html.parser方式解析html
        bus_name = Soup3.find('div', class_='bus_i_t1').find('h1').get_text()  # 提取線路名
        bus_type = Soup3.find('div', class_='bus_i_t1').find('a').get_text()  # 提取線路屬性
        bus_time = Soup3.find_all('p', class_='bus_i_t4')[0].get_text()  # 運行時間
        bus_cost = Soup3.find_all('p', class_='bus_i_t4')[1].get_text()  # 票價
        bus_company = Soup3.find_all('p', class_='bus_i_t4')[2].find('a').get_text()  # 公交公司
        bus_update = Soup3.find_all('p', class_='bus_i_t4')[3].get_text()  # 更新時間
        bus_label = Soup3.find('div', class_='bus_label')
        if bus_label:
            bus_length = bus_label.get_text()  # 線路里程
        else:
            bus_length = []
        print(bus_name, bus_type, bus_time, bus_cost, bus_company, bus_update)
        all_line = Soup3.find_all('div', class_='bus_line_top')  # 線路簡介
        all_site = Soup3.find_all('div', class_='bus_line_site')  # 公交站點
        line_x = all_line[0].find('div', class_='bus_line_txt').get_text()[:-9] + all_line[0].find_all('span')[
            -1].get_text()
        sites_x = all_site[0].find_all('a')
        sites_x_list = []  # 上行線路站點
        for site_x in sites_x:
            sites_x_list.append(site_x.get_text())
        line_num = len(all_line)
        if line_num == 2:  # 若是存在環線,也返回兩個list,只是其中一個爲空
            line_y = all_line[1].find('div', class_='bus_line_txt').get_text()[:-9] + all_line[1].find_all('span')[
                -1].get_text()
            sites_y = all_site[1].find_all('a')
            sites_y_list = []  # 下行線路站點
            for site_y in sites_y:
                sites_y_list.append(site_y.get_text())
        else:
            line_y, sites_y_list = [], []
        information = [bus_name, bus_type, bus_time, bus_cost, bus_company, bus_update, bus_length, line_x, sites_x_list,
                       line_y, sites_y_list]
        Network_list.append(information)


# 定義保存函數,將運算結果保存爲txt文件
def text_save(content, filename, mode='a'):
    file = open(filename, mode, encoding='utf-8')
    for i in range(len(content)):
        file.write(str(content[i]) + '\n')
    file.close()

# 輸出處理後的數據
text_save(Network_list, 'Network_bus.txt')

 

 

3.對爬了的數據進行文本分析,生成詞雲。

 (1)首先打開爬取的數據的文件,經過jieba分詞進行分詞並經過空格分隔,而後生成詞雲。

代碼:

from PIL import Image, ImageSequence
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import jieba
# 讀入背景圖片
abel_mask = np.array(Image.open("./公交車.jpg"))

# 讀取要生成詞雲的文件
path = open('Network_bus.txt',encoding='utf-8').read()

# 經過jieba分詞進行分詞並經過空格分隔
wordlist_after_jieba = jieba.cut(path, cut_all=True)
wl_space_split = " ".join(wordlist_after_jieba)
my_wordcloud = WordCloud().generate(wl_space_split)
my_wordcloud = WordCloud(
    background_color='white',  # 設置背景顏色
    mask=abel_mask,  # 設置背景圖片
    max_words=200,  # 設置最大現實的字數
    font_path='C:/Users/Windows/fonts/simkai.ttf',
    max_font_size=50,
    random_state=30,  # 設置有多少種隨機生成狀態,即有多少種配色方案
    scale=.5,
).generate(wl_space_split)

# 根據圖片生成詞雲顏色
image_colors = ImageColorGenerator(abel_mask)
# my_wordcloud.recolor(color_func=image_colors)

# 如下代碼顯示圖片
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

4.對文本分析結果進行解釋說明。

個人圖片是:

文本獲取到的字符信息並非咱們想要的效果,所以,爲了達到咱們想要的效果,我就將所獲取到的文本信息,生成一個詞雲圖,咱們更加直觀的觀察到咱們

 

5.寫一篇完整的博客,描述上述實現過程、遇到的問題及解決辦法、數據分析思想及結論。

遇到的問題:

一、開始沒法安裝wordcloud

解決辦法:在網站https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud下載wordcloud-1.4.1-cp36-cp36m-win32.whl

而後在終端pip install wordcloud-1.4.1-cp36-cp36m-win32.whl

二、安裝完wordcloud-1.4.1-cp36-cp36m-win32.whl 沒法導入wordcloud

解決方法:經過網上查找我找到了以下的辦法::

打開項目選擇file-->settings...-->project-projiect interpreter右邊選擇上方長條框,選擇Show All...,接着選擇System Interpreter就能夠了

數據分析思想及結論:

個人數據分析是打開我爬取的數據文件,而後經過結巴進行分詞,最後生成詞雲。

結論:在作大做業的過程當中,經過遇到問題而後找到解決問題的方法,我對爬蟲有了進一步的瞭解,同時,也能從中發現本身的不足就是:對經過結巴進行數據分析不熟練。

6.最後提交爬取的所有數據、爬蟲及數據分析源代碼。

所有代碼:

import requests  ##導入requests
from bs4 import BeautifulSoup  ##導入bs4中的BeautifulSoup
from PIL import Image, ImageSequence
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import jieba

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'}
all_url ='http://heyuan.8684.cn/' ##開始的URL地址
start_html = requests.get(all_url, headers=headers)
#print(start_html.text)
Soup = BeautifulSoup(start_html.text, 'html.parser')
all_1 = Soup.find('div', class_='bus_kt_r1').find_all('a')#獲取以數字開頭全部路線
Network_list = []
for a in all_1:
    href = a['href']  # 取出a標籤的href 屬性
    html = all_url + href
    second_html = requests.get(html, headers=headers)
    #print(second_html.text)
    Soup2 = BeautifulSoup(second_html.text, 'html.parser')
    all_a2 = Soup2.find('div', class_='stie_list').find_all('a')
    for a2 in all_a2:
        title1 = a2.get_text()  # 取出a1標籤的文本
        href1 = a2['href']  # 取出a標籤的href 屬性
   # print(title1, href1)
        html_bus = all_url + href1  # 構建線路站點url
        thrid_html = requests.get(html_bus, headers=headers)
        Soup3 = BeautifulSoup(thrid_html.text, 'html.parser')  # 以html.parser方式解析html
        bus_name = Soup3.find('div', class_='bus_i_t1').find('h1').get_text()  # 提取線路名
        bus_type = Soup3.find('div', class_='bus_i_t1').find('a').get_text()  # 提取線路屬性
        bus_time = Soup3.find_all('p', class_='bus_i_t4')[0].get_text()  # 運行時間
        bus_cost = Soup3.find_all('p', class_='bus_i_t4')[1].get_text()  # 票價
        bus_company = Soup3.find_all('p', class_='bus_i_t4')[2].find('a').get_text()  # 公交公司
        bus_update = Soup3.find_all('p', class_='bus_i_t4')[3].get_text()  # 更新時間
        bus_label = Soup3.find('div', class_='bus_label')
        if bus_label:
            bus_length = bus_label.get_text()  # 線路里程
        else:
            bus_length = []
        print(bus_name, bus_type, bus_time, bus_cost, bus_company, bus_update)
        all_line = Soup3.find_all('div', class_='bus_line_top')  # 線路簡介
        all_site = Soup3.find_all('div', class_='bus_line_site')  # 公交站點
        line_x = all_line[0].find('div', class_='bus_line_txt').get_text()[:-9] + all_line[0].find_all('span')[
            -1].get_text()
        sites_x = all_site[0].find_all('a')
        sites_x_list = []  # 上行線路站點
        for site_x in sites_x:
            sites_x_list.append(site_x.get_text())
        line_num = len(all_line)
        if line_num == 2:  # 若是存在環線,也返回兩個list,只是其中一個爲空
            line_y = all_line[1].find('div', class_='bus_line_txt').get_text()[:-9] + all_line[1].find_all('span')[
                -1].get_text()
            sites_y = all_site[1].find_all('a')
            sites_y_list = []  # 下行線路站點
            for site_y in sites_y:
                sites_y_list.append(site_y.get_text())
        else:
            line_y, sites_y_list = [], []
        information = [bus_name, bus_type, bus_time, bus_cost, bus_company, bus_update, bus_length, line_x, sites_x_list,
                       line_y, sites_y_list]
        Network_list.append(information)


# 定義保存函數,將運算結果保存爲txt文件
def text_save(content, filename, mode='a'):
    file = open(filename, mode, encoding='utf-8')
    for i in range(len(content)):
        file.write(str(content[i]) + '\n')
    file.close()

# 輸出處理後的數據
text_save(Network_list, 'Network_bus.txt')

# 讀入背景圖片
abel_mask = np.array(Image.open("./公交車.jpg"))

# 讀取要生成詞雲的文件
path = open('Network_bus.txt',encoding='utf-8').read()

# 經過jieba分詞進行分詞並經過空格分隔
wordlist_after_jieba = jieba.cut(path, cut_all=True)
wl_space_split = " ".join(wordlist_after_jieba)
my_wordcloud = WordCloud().generate(wl_space_split)
my_wordcloud = WordCloud(
    background_color='white',  # 設置背景顏色
    mask=abel_mask,  # 設置背景圖片
    max_words=200,  # 設置最大現實的字數
    font_path='C:/Users/Windows/fonts/simkai.ttf',
    max_font_size=50,
    random_state=30,  # 設置有多少種隨機生成狀態,即有多少種配色方案
    scale=.5,
).generate(wl_space_split)

# 根據圖片生成詞雲顏色
image_colors = ImageColorGenerator(abel_mask)
# my_wordcloud.recolor(color_func=image_colors)

# 如下代碼顯示圖片
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息