1. 程式人生 > >簡單小爬蟲(一)

簡單小爬蟲(一)

為了完成期末作業打算去爬一下漫畫臺這個網站

http://www.manhuatai.com/zhiyinmanke.html

一個挺不錯的網站

目標是爬取漫畫臺主要模組版塊的漫畫名稱

然後輸入漫畫名稱來檢視漫畫章節

首先使用的是python3 

from bs4 import BeautifulSoup as bs 
from urllib import request

來介紹一下beautifulsoup 庫包

eautiful Soup提供一些簡單的、python式的函式用來處理導航、搜尋、修改分析樹等功能。它是一個工具箱,通過解析文件為使用者提供需要抓取的資料,因為簡單,所以不需要多少程式碼就可以寫出一個完整的應用程式。
Beautiful Soup自動將輸入文件轉換為Unicode編碼,輸出文件轉換為utf-8編碼。你不需要考慮編碼方式,除非文件沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然後,你僅僅需要說明一下原始編碼方式就可以了。
Beautiful Soup已成為和lxml、html6lib一樣出色的python直譯器,為使用者靈活地提供不同的解析策略或強勁的速度。

來介紹一下urllib 庫包

使用urllib庫包中的request模擬瀏覽器傳送請求

開始吧

匯入庫包

from bs4 import BeautifulSoup as bs 
from urllib import request

from bs4 import BeautifulSoup as bs  #將匯入的模組命名為bs方便後面使用

模擬瀏覽器傳送請求

def get_url(url):
	headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
	request1 = request.Request(url, headers=headers) 
	respond=request.urlopen(request1)
	html=respond.read().decode('utf-8')
	return html

設定頭部資訊讓模擬更加真實

檢視瀏覽器hearer資訊

谷歌瀏覽器右鍵 ->檢查->

request.Request(url,header=)

第一個引數是網站地址  第二引數傳入一個字典

返回一個request物件

respond=request.urlopen(request1)

使用返回request物件的urlopen()方法傳送請求

得到返回的網頁程式碼可以使用

print(request.urlopen())列印網頁程式碼

檢視網頁的編碼方式


html=respond.read().decode('utf-8')
	return html

此網頁是使用utf-8的編碼

使用decode('utf-8')

解碼 變成unicode編碼

並返回網頁程式碼

第二步 將網頁程式碼使用beautifulsoup 解析網頁程式碼

將網頁程式碼通過標籤的層級關係解析成樹形結構方便搜尋

def parser_html(html):
	#print(html)
	soup=bs(html,'html.parser')#建立beautisoup物件,
	ul_list=soup.find_all('a',class_='sdiv')
	page_dic={'':''}#儲存連結與漫畫名稱
	for i in ul_list:
		print(i['href'],i['title'])
		page_dic[str(i['href'])]=i['title']
	for k,v in page_dic.items():
			print(k,v)
	return page_dic
首先建立beautifulsoup物件

有兩個引數第一個引數是網頁程式碼,第二個是解析模式

返回物件

通過使用物件的fina_all()方法,會返回一個resultset集合元素為tag物件

檢視網頁程式碼發現:


資料是這樣隱藏在這裡的  a標籤   class名稱為sdiv中

於是便使用find_all(a,class="sdiv"    尋找標籤

儲存在page_dic 這個字典中連結作為鍵,名稱作為值

使用迴圈輸出資料


第三步通過輸入的名稱組合成新的url地址

def href_comb(page_dic):
	href='http://www.manhuatai.com'
	name=input('請輸入漫畫名')
	for k,v in page_dic.items():
		if(name==v):
			print(name)
			href1=k
	return href+href1

有沒有發現什麼規律?

我們就只需將我們的字典中的‘鍵’組合進去再發送請求就可以獲得網頁程式碼了

第四步 再次向伺服器傳送請求

href=href_comb(page_dic)
		print(href)
		topic_html=get_url(href)

第五步  再次進行解析

def search_top(html):
	s=bs(html,'html.parser')
	topic1=s.find_all('ul',id='topic1')
	#print(len(topic1))
	topic1_a=topic1[0].find_all('a')
	for i_a in topic1_a:
		print(i_a.string)

先找到ul id 名稱的標籤,然後再尋找a標籤

並列印


任務完成

附上全部程式碼

from bs4 import BeautifulSoup as bs 
from urllib import request
import urllib
from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
def get_url(url):
	headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
	request1 = request.Request(url, headers=headers) 
	respond=request.urlopen(request1)
	html=respond.read().decode('utf-8')
	return html



def parser_html(html):
	#print(html)
	soup=bs(html,'html.parser')#建立beautisoup物件,
	ul_list=soup.find_all('a',class_='sdiv')
	print(type(ul_list))
	page_dic={'':''}#儲存連結與漫畫名稱
	for i in ul_list:
		print(i['href'],i['title'])
		page_dic[str(i['href'])]=i['title']
	for k,v in page_dic.items():
			print(k,v)
	return page_dic

'''
取出網站,進行拼接

'''
def href_comb(page_dic):
	href='http://www.manhuatai.com'
	while 1:
		try:
			name=input('請輸入漫畫名')
			for k,v in page_dic.items():
				if(name==v):
					print(name)
					href1=k
					return href+href1
		except Exception as e:
			print("輸入不規範,請重新輸入")
				


		
'''
尋找章節
'''
def search_top(html):
	s=bs(html,'html.parser')
	topic1=s.find_all('ul',id='topic1')
	print(len(topic1))
	topic1_a=topic1[0].find_all('a')
	for i_a in topic1_a:
		print(i_a.string,i_a['href'])
	while 1:
		try:
			srting_top=input("請輸入需要檢視的章節")
			for i_a in topic1_a:
				if srting_top==i_a.string:
					return 'http://www.manhuatai.com'+i_a['href']
		except Exception as e:
			print("輸入錯誤,請再次輸入需要檢視的章節")
		
	
	'''
尋找圖片連結
'''


if __name__ == '__main__':
	while 1:
		html=get_url('http://www.manhuatai.com/zhiyinmanke.html')
		page_dic=parser_html(html)
		href=href_comb(page_dic)
		print(href)
		topic_html=get_url(href)
		topic_href=search_top(topic_html)
		print(topic_href)
		get_pict_src(topic_href)
		#save_picture(get_pict_src(topic_href))
		targer=input("是否退出,退出請輸入1,繼續檢視請輸入2")
		if targer==1:
			break
	#