Python自學(xué)指南 | 怎樣把最好用的Python教程爬取下來(lái)?
很多Python初學(xué)者都是從廖雪峰的Python教程開(kāi)始的。我也是廖老師教程的忠實(shí)讀者。今天學(xué)到了爬蟲(chóng),就想把廖老師的教程爬取下來(lái),方便查閱。下面是我爬取這個(gè)教程的簡(jiǎn)單過(guò)程。
一個(gè)簡(jiǎn)單的爬蟲(chóng)大概包含下面的4個(gè)步驟:
1.獲取網(wǎng)頁(yè)的URL
2.下載網(wǎng)頁(yè)的HTML文件
3.解析下載到的HTML,提取所需的數(shù)據(jù)
4.將提取的數(shù)據(jù)存儲(chǔ)起來(lái)
首先,看一下如何獲取廖老師教程的全部URL。在瀏覽器中打開(kāi)教程的首頁(yè),查看源文件,發(fā)現(xiàn)教程的URL如下圖所示:
從源文件中可以看到,每篇教程都是由兩串隨機(jī)碼組成的(是不是隨機(jī)的我不確定,水平有限不知道這些代碼是怎么生成的)。因此,要爬取所有的教程頁(yè)面,則需要先將各頁(yè)面的URL提取出來(lái),然后與根url組合,獲得完整的URL。觀察整個(gè)HTML, URL所在的div標(biāo)簽具備唯一的class屬性值“x-sidebar-left-content”,就根據(jù)這個(gè)特征解析首頁(yè)的代碼,獲得URL列表。使用BeautifulSoup解析獲取的各頁(yè)面的URL和標(biāo)題。
def bs_parser(html):
tree = BeautifulSoup(html, 'lxml')
data = tree.find('div', class_='x-sidebar-left-content').find_all('a')
urls = []
titles = []
grades = []
for item in data:
urls.append(item.attrs['href'])
titles.append(item.get_text())
return urls, titles
接下來(lái),將獲得的URL與根URL組合,獲得完整的URL。使用Python的urllib.request包抓取所有的頁(yè)面的HTML。
def download(url):
print("Downloading: %s" % url)
try:
result = urllib.request.urlopen(url, timeout=2).read()
except urllib.error.URLError as e:
print("Downloading Error:", e.reason)
result = None
return result
如果要把自己的爬蟲(chóng)偽裝成流量器,也可以給其加上首部的信息(當(dāng)然這里沒(méi)有必要)。
def download_browser(url, headers):
opener = urllib.request.build_opener()
opener.addheaders = headers
print("Downloading: %s" % url)
try:
result = opener.open(url, timeout=2)
result = result.read()
print("Download OK!")
except urllib.request.URLError as e:
print("Downloading error:", e.reason)
result = None
return result
第三步就是要解析抓取的HTML文檔,提取有用的信息了。和第一步中提取URL的方法類似,先分析頁(yè)面的代碼,確定有用信息的特征,然后用BeautifulSoup將其提取出來(lái)。
內(nèi)容部分的特征是div標(biāo)簽具備值為“x-wiki-content”的class屬性,并且在全文中是唯一的。可以利用該屬性來(lái)提取數(shù)據(jù):
def bs_parser_content(html):
tree = BeautifulSoup(html, 'lxml')
data = tree.find('div', class_='x-wiki-content')
result = data.get_text()
return result
最后,將獲取的數(shù)據(jù)寫(xiě)到文本文件中進(jìn)行存儲(chǔ)。一個(gè)簡(jiǎn)單的爬取大神教程的小爬蟲(chóng)算是做完了。
全部的代碼如下:
import urllib, urllib.request, urllib.error
from bs4 import BeautifulSoup
import os
def download(url): # 沒(méi)有偽裝的下載器
print("Downloading: %s" % url)
try:
result = urllib.request.urlopen(url, timeout=2).read()
except urllib.error.URLError as e:
print("Downloading Error:", e.reason)
result = None
return result
def download_browser(url, headers): # 帶瀏覽器偽裝的下載器
opener = urllib.request.build_opener()
opener.addheaders = headers
print("Downloading: %s" % url)
try:
result = opener.open(url, timeout=2)
result = result.read()
print("Download OK!")
except urllib.request.URLError as e:
print("Downloading error:", e.reason)
result = None
return result
# 解析首頁(yè),獲取url
def bs_parser(html):
tree = BeautifulSoup(html, 'lxml')
data = tree.find('div', class_='x-sidebar-left-content').find_all('a')
print(data[0].attrs['href'])
urls = []
titles = []
grades = []
for item in data:
urls.append(item.attrs['href'])
titles.append(item.get_text())
return urls, titles
# 解析頁(yè)面內(nèi)容
def bs_parser_content(html):
tree = BeautifulSoup(html, 'lxml')
data = tree.find('div', class_='x-wiki-content')
# print(data)
result = data.get_text()
return result
# 首頁(yè)url
url = 'http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000'
root = 'http://www.liaoxuefeng.com'
# header一定是一個(gè)元組列表
headers = [
('Connection', 'Keep-Alive'),
('Accept', 'text/html, application/xhtml+xml, */*'),
('Accept-Language', 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3'),
('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko')
]
html = download_browser(url, headers) # 下載首頁(yè)的HTML
urls, titles = bs_parser(html) # 解析首頁(yè)的HTML,返回URL和標(biāo)題
i = 0
for item, title in zip(urls, titles):
i += 1
url = root + item
html = download_browser(url, headers) # 下載頁(yè)面html
result = bs_parser_content(html) # 解析html,獲取數(shù)據(jù)
# 合成文本文件路徑
fileName = str(i) + ' ' + title.replace(r'/', ' ') + '.txt'
fileName = os.path.join('Results/', fileName)
# 將數(shù)據(jù)寫(xiě)入到文本文件
with open(fileName, 'w') as f:
f.write(result)