Python想學爬蟲?不知道怎麼辦,來一步一步教你做

網絡爬蟲又稱網絡蜘蛛,是指按照某種規則在網絡上爬取所需內容的腳本程序。眾所周知,每個網頁通常包含其他網頁的入口,網絡爬蟲則通過一個網址依次進入其他網址獲取所需內容。

優先申明:我們使用的python編譯環境為PyCharm

這是小編準備的python基礎學習資料,關注,轉發,私信小編“01”即可免費領取!

Python想學爬蟲?不知道怎麼辦,來一步一步教你做

正文

一、首先一個網絡爬蟲的組成結構:

爬蟲調度程序(程序的入口,用於啟動整個程序)

url管理器(用於管理未爬取得url及已經爬取過的url)

網頁下載器(用於下載網頁內容用於分析)

網頁解析器(用於解析下載的網頁,獲取新的url和所需內容)

網頁輸出器(用於把獲取到的內容以文件的形式輸出)

二、編寫網絡爬蟲

(1)準備所需庫

我們需要準備一款名為BeautifulSoup(網頁解析)的開源庫,用於對下載的網頁進行解析,我們是用的是PyCharm編譯環境所以可以直接下載該開源庫。

步驟如下:

選擇File->Settings

Python想學爬蟲?不知道怎麼辦,來一步一步教你做

打開Project:PythonProject下的Project interpreter

Python想學爬蟲?不知道怎麼辦,來一步一步教你做

點擊加號添加新的庫

Python想學爬蟲?不知道怎麼辦,來一步一步教你做

輸入bs4選擇bs4點擊Install Packge進行下載

Python想學爬蟲?不知道怎麼辦,來一步一步教你做

(2)編寫爬蟲調度程序

這裡的bike_spider是項目名稱引入的四個類分別對應下面的四段代碼url管理器,url下載器,url解析器,url輸出器。

# 爬蟲調度程序

from bike_spider import url_manager, html_downloader, html_parser, html_outputer

# 爬蟲初始化

class SpiderMain(object):

def __init__(self):

self.urls = url_manager.UrlManager()

self.downloader = html_downloader.HtmlDownloader()

self.parser = html_parser.HtmlParser()

self.outputer = html_outputer.HtmlOutputer()

def craw(self, my_root_url):

count = 1

self.urls.add_new_url(my_root_url)

while self.urls.has_new_url():

try:

new_url = self.urls.get_new_url()

print("craw %d : %s" % (count, new_url))

# 下載網頁

html_cont = self.downloader.download(new_url)

# 解析網頁

new_urls, new_data = self.parser.parse(new_url, html_cont)

self.urls.add_new_urls(new_urls)

# 網頁輸出器收集數據

self.outputer.collect_data(new_data)

if count == 10:

break

count += 1

except:

print("craw failed")

self.outputer.output_html()

if __name__ == "__main__":

root_url = "http://baike.baidu.com/item/Python/407313"

obj_spider = SpiderMain()

obj_spider.craw(root_url)

(3)編寫url管理器

我們把已經爬取過的url和未爬取的url分開存放以便我們不會重複爬取某些已經爬取過的網頁。

# url管理器

class UrlManager(object):

def __init__(self):

self.new_urls = set()

self.old_urls = set()

def add_new_url(self, url):

if url is None:

return

if url not in self.new_urls and url not in self.old_urls:

self.new_urls.add(url)

def add_new_urls(self, urls):

if urls is None or len(urls) == 0:

return

for url in urls:

self.new_urls.add(url)

def get_new_url(self):

# pop方法會幫我們獲取一個url並且移除它

new_url = self.new_urls.pop()

self.old_urls.add(new_url)

return new_url

def has_new_url(self):

return len(self.new_urls) != 0

(4)編寫網頁下載器

通過網絡請求來下載頁面

# 網頁下載器

import urllib.request

class HtmlDownloader(object):

def download(self, url):

if url is None:

return None

response = urllib.request.urlopen(url)

# code不為200則請求失敗

if response.getcode() != 200:

return None

return response.read()

(5)編寫網頁解析器

對網頁進行解析時我們需要知道我們要查詢的內容都有哪些特徵,我們可以打開一個網頁點擊右鍵審查元素來了解我們所查內容的共同之處。

# 網頁解析器

import re

from bs4 import BeautifulSoup

from urllib.parse import urljoin

class HtmlParser(object):

def parse(self, page_url, html_cont):

if page_url is None or html_cont is None:

return

soup = BeautifulSoup(html_cont, "html.parser", from_encoding="utf-8")

new_urls = self._get_new_urls(page_url, soup)

new_data = self._get_new_data(page_url, soup)

return new_urls, new_data

def _get_new_data(self, page_url, soup):

res_data = {"url": page_url}

# 獲取標題

title_node = soup.find("dd", class_="lemmaWgt-lemmaTitle-title").find("h1")

res_data["title"] = title_node.get_text()

summary_node = soup.find("div", class_="lemma-summary")

res_data["summary"] = summary_node.get_text()

return res_data

def _get_new_urls(self, page_url, soup):

new_urls = set()

# 查找出所有符合下列條件的url

links = soup.find_all("a", href=re.compile(r"/item/"))

for link in links:

new_url = link['href']

# 獲取到的url不完整,學要拼接

new_full_url = urljoin(page_url, new_url)

new_urls.add(new_full_url)

return new_urls

(6)編寫網頁輸出器

輸出的格式有很多種,我們選擇以html的形式輸出,這樣我們可以的到一個html頁面。

這是小編準備的python基礎學習資料,關注,轉發,私信小編“01”即可免費領取!

Python想學爬蟲?不知道怎麼辦,來一步一步教你做


分享到:


相關文章: