2018-9月 python3爬取百度百科100個頁面

前陣子開始學習python,剛接觸爬蟲不久,參考其它csdn博客大神的文章簡單做了一個demo

# python3中用urllib.request表示python2中的urllib2
import urllib.request as urllib2
# 運用正則表達式
import re
# urlparse
import urllib.parse as urlparse
# 使用第三方模塊,使用BeautifulSoup
from bs4 import BeautifulSoup as bs
# 請求的url中文解決
from urllib.parse import quote
import string
# 網頁出現錯誤的模塊
from urllib.error import URLError,HTTPError,ContentTooShortError
# 存儲爬取的數據
data={}
# 爬取的url
urls={}

# 下載url
def download(url):
    print("download..."+url)
    # 對url錯誤作異常處理
    try:
        html= urllib2.urlopen(url)
    except(URLError,HTTPError,ContentTooShortError) as e:
        print("download error:"+e.reason)
        html=None
    return html


# 解析拿到的url
def parser_html(url,response):
    soup = bs(response, 'html.parser')
    return soup


# 打印出信息
def out_information(soup):
    try:
        # 打印出title標籤的內容
        data['title']=soup.title.string
        summary_node = soup.find('div', class_="lemma-summary")
        data['summary']=summary_node.get_text()
        print('爬取的標題:'+data['title'])
        print('爬取的內容:')
        print(data['summary'])
    except:
        print('無法獲取內容')


def get_new_urls(page_url, soup):
    # 存放從入口頁面拿到的url集合
    new_urls = set()
    count=1
    # 正則匹配所有/item/鏈接
    links = soup.find_all('a', href=re.compile(r"/item/"))
    for link in links:
        # 控制數量,需要手動作更改,這裏爲了使爬取一百條,將count改到了119
        # 手動控制的,具體的原因還不清楚
        if(count<119):
            new_url = link['href']
            #urljoin 函數可以將new_url 按page_url 的格式拼接成一個全新的url
            new_full_url = urlparse.urljoin(page_url,new_url)
            new_urls.add(new_full_url)
            # 每拼接完一個頁面就加1
            count=count+1

    return new_urls


#    程序入口,注意是雙下劃線
if __name__=="__main__":
    # 記錄頁面數
    count = 1
    # 爬蟲入口頁面
    url = "https://baike.baidu.com/item/%E8%8B%B1%E8%AF%AD/109997"
    # 下載url
    response=download(url)
    # 解析網頁
    soup=parser_html(url,response)
    # 打印內容
    out_information(soup)
    # 獲取需要爬取的url集合
    urls=get_new_urls(url,soup)
    print(urls)
    for url in urls:
        # 將頁面數轉換爲字符串形式
        srt_count = str(count)
        print('爬取第' + srt_count + '個頁面:')
        # 下載url
        response = download(url)
        # 解析網頁
        soup = parser_html(url, response)
        # 打印內容
        out_information(soup)
        # 爬完一個頁面就加一
        count=count+1

每天進步一點點,開心也多一點點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章