random:生成隨機數html
requests:發送請求獲取網頁信息python
fake-useragent:生成代理服務器正則表達式
json:數據轉換數據庫
re:用於正則匹配json
bs4:數據過濾api
matpotlib:圖像處理瀏覽器
worldcloud:生成詞雲服務器
numpy:圖像處理app
PIL:圖像處理dom
jieba:對中文進行分詞(本次未用到)
使用代碼模擬瀏覽器發送請求-->瀏覽器返回信息(html/json)-->提取有用的信息-->進行儲存
使用代碼向目標站點發送請求,即發送一個Request
請求應包含:請求頭、請求體等
發送請求成功後,會得到站點返回的信息(Response)
解析html數據:正則表達式(RE模塊),第三方解析庫如Beautifulsoup,pyquery,xpath等
解析json數據:json模塊
以文件存儲
存入數據庫
爲了防止屢次訪問某站點致使IP被封,對IP進行假裝。
找一些提供免費IP的網站爬取IP數據存儲到本地文件中,將爬蟲進行到底。
1 # __Author__ :"Chen Yang" 2 # __Time__: 2019/8/22 20:56 3 4 import requests 5 from fake_useragent import UserAgent 6 import re 7 8 9 def create_pool(ur): 10 url = ur 11 12 ua = UserAgent() 13 # fake_useragent 提供的隨機生成代理服務器 14 headers = {"User-Agent": ua.random} 15 16 r = requests.get(url, headers=headers) 17 # 正則匹配全部IP 18 comment = re.findall('<td data-title="IP">(.*)</td>', r.text) 19 # 正則匹配全部端口 20 port = re.findall('<td data-title="PORT">(.*)</td>', r.text) 21 22 print(r.text) 23 print(comment) 24 print(port) 25 # 將IP和端口對應 存入文件 26 with open('ip-port.text', 'a', encoding='utf-8') as f: 27 for i in range(len(comment) - 1): 28 f.write(comment[i] + ":" + port[i]) 29 f.write('\n') 30 31 32 if __name__ == "__main__": 33 # 爬取該網頁前7頁IP 34 for i in range(6): 35 ur = 'http://www.qydaili.com/free/?action=china&page=' + str(i) 36 create_pool(ur)
xhr:XMLHttpRequest 對象提供了對 HTTP 協議的徹底的訪問,包括作出 POST 和 HEAD 請求以及普通的 GET 請求的能力。
某條文章是動態隨機推薦的,每次進入頭條頁面的文章都不一樣。
在屢次分析後找到realtime_news/的xhr
訪問open_url,爬取標籤
至此,基本能夠肯定realtime_news的xhr就是要爬的文件。
思路:爬取realtime_news的xhr的文件-->獲取其中open_url-->爬取標籤-->生成詞雲
1 import random 2 import requests 3 from fake_useragent import UserAgent 4 import json 5 import re 6 from bs4 import BeautifulSoup 7 import matplotlib.pyplot as plt # 用於圖像處理 8 from wordcloud import WordCloud# 用於生成詞雲 9 import numpy as np 10 from PIL import Image 11 12 # 詞雲形狀文件 須要替換成你本地的圖片 13 backgroud_Image = np.array(Image.open("man.jpg")) 14 # 詞雲字體 須要替換成你本地的字體 15 WC_FONT_PATH = '黃引齊招牌體.ttf' 16 17 18 def get_ip(): 19 f = open("ip-port.text", 'r') # 從IP-port中讀取IP 20 ip_all = [] 21 for k in f: 22 line = f.readline() 23 ip_all.append(line[:-1]) # 去除/n 24 f.close() 25 # print(ip_all) 26 i = random.randint(0, len(ip_all)-1) 27 pr = ip_all[i] 28 print("ip地址爲:{}".format(pr)) 29 return pr 30 31 32 def get_info(): 33 ''' 34 使用爬取的ip來進行ip代理 35 使用fake_useragent進行服務器代理,防止IP被封 36 ''' 37 url = 'https://www.toutiao.com/api/pc/realtime_news/' 38 39 ua = UserAgent() 40 agent = ua.random 41 print("代理爲:{}".format(agent)) 42 header = {"User-Agent": agent} 43 44 ip = get_ip() 45 proxies = {'url': ip} 46 47 try: 48 # 獲取首頁信息 49 r = requests.get(url, headers=header, proxies=proxies) 50 global_json = json.loads(r.text) 51 print(global_json) 52 except: 53 print("請求頭條主頁失敗") 54 55 # 獲取首頁信息動態推薦文章的地址 56 article = [] 57 for i in range(len(global_json['data'])): 58 article.append(global_json['data'][i]['open_url']) 59 # 頭條得子文章頁標號 會隨機發生變化 60 #print(article) 61 62 # 取8篇文章得label 63 for i in range(7): 64 # 訪問動態推薦文章地址 65 content = "http://toutiao.com" + article[i] 66 try: 67 respon = requests.get(content, headers=header, proxies=proxies) 68 # 輸入返回對象的文本值 69 # print(respon.text) 70 except: 71 print("請求文章失敗") 72 73 # 指定編碼等於原始頁面編碼 74 respon.encoding = respon.apparent_encoding 75 # 獲取想要地址對應的BeautifulSoup 76 html = BeautifulSoup(respon.text, 'lxml') 77 # 選擇 第六個script標籤 即數據所在標籤 78 try: 79 src = html.select('script')[6].string 80 #print(src) 81 except: 82 print("獲取數據失敗!") 83 result = [] 84 try: 85 # 正則找到數據中標籤字段 86 labels = re.findall('tags:(.*),', respon.text) 87 #print(type(labels)) 88 # strip()去空格 89 # 把字符串轉爲列表 90 result = labels[0].strip() 91 # print(type(result)) 92 # print(labels) 93 # eval() 將字符串列表 轉爲列表 94 result = eval(result) 95 # print(result) 96 except: 97 print("未得到labels") 98 with open("labels.json", 'a', encoding='utf-8') as f: 99 for i in range(len(result)-1): 100 f.write(result[i]['name']) 101 f.write(' ') 102 103 104 def cut_word(): 105 ''' 106 生成詞雲 107 :return: 108 ''' 109 with open("labels.json", 'r', encoding='utf-8') as f: 110 label =f.read() 111 wl = "".join(label) 112 print(wl) 113 return wl 114 115 116 def create_word_cloud(): 117 ''' 118 生成詞雲 119 :return: 120 ''' 121 # 設置詞雲形狀圖片 122 #wc_mask = np.array(WC_MASK_IMG) 123 # 設置詞雲配置 字體 背景 大小等 124 wc = WordCloud(background_color='white', max_words=2000, mask=backgroud_Image, scale=4, 125 max_font_size=50, random_state=42, font_path=WC_FONT_PATH) 126 # 生成詞雲 127 wc.generate(cut_word()) 128 129 # 在只設置mask狀況下, 你會獲得一個圖片形得詞雲 130 plt.imshow(wc, interpolation='bilinear') 131 #plt.axis("off") 132 plt.figure() 133 plt.show() 134 135 136 if __name__ == '__main__': 137 get_info() 138 create_word_cloud()