99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python使用正則表達式獲取網(wǎng)頁中所需要的信息
Python使用正則表達式獲取網(wǎng)頁中所需要的信息
2018-07-21
收藏

Python使用正則表達式獲取網(wǎng)頁中所需要的信息

使用正則表達式的幾個步驟:
1、用import re 導入正則表達式模塊;
2、用re.compile()函數(shù)創(chuàng)建一個Regex對象;
3、用Regex對象的search()或findall()方法,傳入想要查找的字符串,返回一個Match對象;
4、調(diào)用Match對象的group()方法,返回匹配到的字符串。
在交互式環(huán)境中簡單嘗試一下,查詢字符串中的固話:    
import re
text = '小明家的固話是0755-123456,而小麗家的固話時0789-654321,小王家的電話是123456789'#用于檢測的字符串
ph_re = re.compile(r'\d{4}?-\d+') #創(chuàng)建Regex對象,匹配幾種電話的方式,\d表示0-9的數(shù)字,{4}表示前面的匹配4次,?表示可選,+表示出現(xiàn)1次或多次。
matchs1 = ph_re.findall(text) #findall()表示查找所有匹配項,返回一個字符串
matchs2 = ph_re.search(text)#search(),查找第一次匹配的文本,返回一個對象。
print(matchs1)
print(matchs2)
matchs2.group()
返回的結果,是這樣的:
findall()方法返回的是一個字符串,可以直接打印出來。而search()方法返回的是一個對象,所以打印出來的是是如圖的第二行。
調(diào)用group(),對象返回匹配的結果。
最后,小王的電話之所以沒有匹配到,是因為'-'沒有進行可選即在其后加上‘?'。
下面進行一個小的實驗,獲取某個網(wǎng)頁中所有的http/https網(wǎng)址,并計算有多少個。
首先是獲取HTML文件。這里要用到requests模塊。    
# -*- coding: utf-8 -*-
import requests
import re
def get_html(url):
 res = requests.get(url)
 res.encoding = 'utf-8'
 html = res.text
 return html
這里get_html函數(shù)返回的,其實就類似上面例子中的text,用來匹配的文本。
然后,創(chuàng)建正則表達式:    
def get_addr(response):
  addr_regex = re.compile(r'''(
   (http://|https://)?  #http/https
   (www)?
   (\.[a-z1-9A-Z]+)
   (\.com|\.cn)
   )''',re.VERBOSE)#匹配網(wǎng)址,
  matchs = []
  for groups in addr_regex.findall(response):
   matchs.append(groups[0])
  if len(matchs) == 0:
   print('沒有網(wǎng)址')  
  return matchs
這里向re.compile(),傳入變量re.VERBOSE,作為第二個參數(shù),可以將正則表達式放在多行,并進行注釋,如上。
返回一個matchs列表對象。
再來個啟動函數(shù)。    
def start():
  url = 'http://news.163.com/18/0127/18/D966K4CO0001899N.html'
  a = get_html(url)
  b = get_addr(a)
  print('\n'.join(b))
  print(str(len(b)))
  print('ok')
if __name__ == '__main__':
  start()
這里傳入的url是我隨意找的一個新聞鏈接。
然后調(diào)用get_html()和get_addr(),就得到了想要的東西。str(len(b)),為統(tǒng)計的數(shù)量。
測試的結果是類似這樣的:
這里似乎獲取一些URL,沒什么卵用。。。但是,如果結合前面的查詢新聞列表的方式,獲取批量url,
而創(chuàng)建的正則是xxx.jpg,然后調(diào)用os模塊,os.mkdir(folder)、os.chdir(folder),將獲取到的匹配結果寫入文件,放入某個文件夾。
那么就可以實現(xiàn),從某些網(wǎng)站上批量獲取jpg圖片,然后存入某個文件夾的爬蟲功能。實測,可行!
總結
以上所述是小編給大家介紹的Python使用正則獲取網(wǎng)頁中所需要的信息,希望對大家有所幫助

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }