亚洲熟女综合色一区二区三区,亚洲精品中文字幕无码蜜桃,亚洲va欧美va日韩va成人网,亚洲av无码国产一区二区三区,亚洲精品无码久久久久久久

Python自學(xué)指南 | 怎樣把最好用的Python教程爬取下來?

很多Python初學(xué)者都是從廖雪峰的Python教程開始的。我也是廖老師教程的忠實讀者。今天學(xué)到了爬蟲,就想把廖老師的教程爬取下來,方便查閱。下面是我爬取這個教程的簡單過程。

一個簡單的爬蟲大概包含下面的4個步驟:
1.獲取網(wǎng)頁的URL
2.下載網(wǎng)頁的HTML文件
3.解析下載到的HTML,提取所需的數(shù)據(jù)
4.將提取的數(shù)據(jù)存儲起來

首先,看一下如何獲取廖老師教程的全部URL。在瀏覽器中打開教程的首頁,查看源文件,發(fā)現(xiàn)教程的URL如下圖所示:

Python自學(xué)指南 | 怎樣把最好用的Python教程爬取下來?
Paste_Image.png

從源文件中可以看到,每篇教程都是由兩串隨機碼組成的(是不是隨機的我不確定,水平有限不知道這些代碼是怎么生成的)。因此,要爬取所有的教程頁面,則需要先將各頁面的URL提取出來,然后與根url組合,獲得完整的URL。觀察整個HTML, URL所在的div標簽具備唯一的class屬性值“x-sidebar-left-content”,就根據(jù)這個特征解析首頁的代碼,獲得URL列表。使用BeautifulSoup解析獲取的各頁面的URL和標題。

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

接下來,將獲得的URL與根URL組合,獲得完整的URL。使用Python的urllib.request包抓取所有的頁面的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

如果要把自己的爬蟲偽裝成流量器,也可以給其加上首部的信息(當(dāng)然這里沒有必要)。

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的方法類似,先分析頁面的代碼,確定有用信息的特征,然后用BeautifulSoup將其提取出來。

Python自學(xué)指南 | 怎樣把最好用的Python教程爬取下來?
Paste_Image.png

內(nèi)容部分的特征是div標簽具備值為“x-wiki-content”的class屬性,并且在全文中是唯一的??梢岳迷搶傩詠硖崛?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ù)寫到文本文件中進行存儲。一個簡單的爬取大神教程的小爬蟲算是做完了。

全部的代碼如下:

import urllib, urllib.request, urllib.error
from bs4 import BeautifulSoup
import os

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

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

# 解析首頁,獲取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 

# 解析頁面內(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

# 首頁url
url = 'http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000'
root = 'http://www.liaoxuefeng.com'

# header一定是一個元組列表
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) # 下載首頁的HTML
urls, titles = bs_parser(html) # 解析首頁的HTML,返回URL和標題
i = 0
for item, title in zip(urls, titles):
    i += 1
    url = root + item
    html = download_browser(url, headers) # 下載頁面html
result = bs_parser_content(html) # 解析html,獲取數(shù)據(jù)
# 合成文本文件路徑
    fileName = str(i) + ' ' + title.replace(r'/', ' ') + '.txt'
fileName = os.path.join('Results/', fileName)
# 將數(shù)據(jù)寫入到文本文件
    with open(fileName, 'w') as f:
        f.write(result)

相關(guān)新聞

歷經(jīng)多年發(fā)展,已成為國內(nèi)好評如潮的Linux云計算運維、SRE、Devops、網(wǎng)絡(luò)安全、云原生、Go、Python開發(fā)專業(yè)人才培訓(xùn)機構(gòu)!