【Python】抓取網(wǎng)頁信息

最近開始利用python實操抓取網(wǎng)頁鏈接內(nèi)容,記錄學習過程,熟悉python操作。

版本:Python 3.6.0
IDE:PyCham

獲取網(wǎng)頁內(nèi)容思路:
1、獲取網(wǎng)頁源代碼
2、篩選出需要的信息

需要技能:
基礎(chǔ)python的語法規(guī)則
正則表達式基礎(chǔ)信息

通過Python把頁面內(nèi)容讀取出來。

import urllib.request  #接入頁面讀取模塊
import re  #接入正則表達式模塊

#獲取鏈接的內(nèi)容
def getHtml(url):   
    page = urllib.request.urlopen(url)   #獲取鏈接的全部內(nèi)容
    html = page.read()   #讀取鏈接內(nèi)容
    return html

大部分頁面內(nèi)容是不需要的,通過用正則表達式篩選出需要的信息。

#獲取標題
def getTitle(html):
    reg = r'jpg" alt="(.+?)"'   #定義要獲取的文字截取部分
    titlere =  re.compile(reg)    #提取提取到的文字部分
    html = html.decode('utf-8')  # python3
    titlelist = re.findall(titlere, html)   #提取內(nèi)容以數(shù)據(jù)形式保存
    return titlelist

#獲取樓盤名
def getLouPan(html):
    reg = r'data-el="region">(.+?)</a>'
    LouPanre = re.compile(reg)
    html = html.decode('utf-8')
    LouPanlist = re.findall(LouPanre, html)
    return LouPanlist

#獲取樓盤總價
def getPrice(html):
    reg = r'class="totalPrice"><span>(.+?)</span>'
    Pricere = re.compile(reg)
    html = html.decode('utf-8')
    Pricelist = re.findall(Pricere, html)
    return Pricelist

#獲取樓盤面積
def getSquare(html):
    reg = r'data-el="region">.+?</a>(.+?)</div></div><div class="flood">'
    Squarere = re.compile(reg)
    html = html.decode('utf-8')
    Squarelist = re.findall(Squarere, html)
    return Squarelist

#獲取樓盤均價
def getAvePrice(html):
    reg = r'data-price=".+?"><span>單價(.+?)元/平米</span>'
    AvePricere = re.compile(reg)
    html = html.decode('utf-8')
    AvePricelist = re.findall(AvePricere, html)
    return AvePricelist

#獲取樓盤詳情鏈接
def getDetailurl(html):
    reg = r'<div class="title"><a class="" href="(.+?)"'
    Detailurl = re.compile(reg)
    html = html.decode('utf-8')
    Detailurllist = re.findall(Detailurl, html)
    return Detailurllist

#獲取樓盤編號
def getHouseID(html):
    reg = r'<div class="title"><a class="" href="https://gz\.lianjia\.com/ershoufang/(.+?)\.html"'
    HouseID = re.compile(reg)
    html = html.decode('utf-8')
    HouseIDlist = re.findall(HouseID, html)
    return HouseIDlist

這樣就基本抓取完所有我想要的信息了??梢园逊祷氐臄?shù)列做個變量,方便之后的操作了。

html = getHtml("https://gz.lianjia.com/ershoufang/p1/")
Title = getTitle(html)
Loupan = getLouPan(html)
Price = getPrice(html)
Square = getSquare(html)
AvePrice = getAvePrice(html)
Detailurl = getDetailurl(html)
HouseID = getHouseID(html)

下一篇將記錄把抓取回來的數(shù)據(jù)插入到數(shù)據(jù)庫里。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容