免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
[python] 常用正則表達式爬取網(wǎng)頁信息及分析HTML標簽總結(jié)

轉(zhuǎn)自:http://blog.csdn.net/eastmount/article/details/51082253

這篇文章主要是介紹Python爬取網(wǎng)頁信息時,經(jīng)常使用的正則表達式及方法。它是一篇總結(jié)性文章,實用性比較大,主要解決自己遇到的爬蟲問題,也希望對你有所幫助~
當然如果會Selenium基于自動化測試爬蟲、BeautifulSoup分析網(wǎng)頁DOM節(jié)點,這就更方便了,但本文更多的是介紹基于正則的底層爬取分析。

涉及內(nèi)容如下:

 

  • 常用正則表達式爬取網(wǎng)頁信息及HTML分析總結(jié)
    • 1.獲取<tr></tr>標簽之間內(nèi)容
    • 2.獲取<a href..></a>超鏈接之間內(nèi)容
    • 3.獲取URL最后一個參數(shù)命名圖片或傳遞參數(shù)
    • 4.爬取網(wǎng)頁中所有URL鏈接
    • 5.爬取網(wǎng)頁標題title兩種方法
    • 6.定位table位置并爬取屬性-屬性值
    • 7.過濾<span></span>等標簽
    • 8.獲取<script></script>等標簽內(nèi)容
    • 9.通過replace函數(shù)過濾<br />標簽
    • 10.獲取<img ../>中超鏈接及過濾<img>標簽

推薦基礎(chǔ)文章:Python正則表達式指南 - AstralWind


------------------------------------------------------------------------------------------------------------------------------

1.獲取<tr></tr>標簽之間內(nèi)容

該部分主要是通過正則表達式獲取兩個標簽之間的內(nèi)容,通常這種標簽都是成對出現(xiàn)的。
開始標簽如:<tr>、<th>、<td>、<a>、<table>、<div>...
后綴標簽如:</tr>、</th>、</td>、</a>、</table>、</div>...

核心代碼:
        res_tr = r'<tr>(.*?)</tr>'
        m_tr =  re.findall(res_tr,language,re.S|re.M)
例子:

[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3.   
  4. language = '''''<tr><th>性別:</th><td>男</td></tr><tr>'''  
  5.   
  6. #正則表達式獲取<tr></tr>之間內(nèi)容  
  7. res_tr = r'<tr>(.*?)</tr>'  
  8. m_tr =  re.findall(res_tr,language,re.S|re.M)  
  9. for line in m_tr:  
  10.     print line  
  11.     #獲取表格第一列th 屬性  
  12.     res_th = r'<th>(.*?)</th>'    
  13.     m_th = re.findall(res_th,line,re.S|re.M)  
  14.     for mm in m_th:  
  15.         print unicode(mm,'utf-8'),  #unicode防止亂  
  16.     #獲取表格第二列td 屬性值  
  17.     res_td = r'<td>(.*?)</td>'  
  18.     m_td = re.findall(res_td,line,re.S|re.M)  
  19.     for nn in m_td:  
  20.         print unicode(nn,'utf-8')  

輸出如下所示:

[python] view plain copy
  1. >>>   
  2. <th>性別:</th><td>男</td>  
  3. 性別: 男  
  4. >>>   

python通過re模塊提供對正則表達式的支持。使用re的一般步驟是先將正則表達式的字符串形式編譯為Pattern實例,然后使用Pattern實例處理文本并獲得匹配結(jié)果(一個Match實例),最后使用Match實例獲得信息,進行其他的操作。

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 搜索string,以列表形式返回全部能匹配的子串。其中RE的常見參數(shù)包括:
        re.I(re.IGNORECASE): 忽略大小寫(括號內(nèi)是完整寫法)
        re.M(re.MULTILINE): 多行模式,改變'^'和'$'的行為
        re.S(re.DOTALL): 點任意匹配模式,改變'.'的行為

 

------------------------------------------------------------------------------------------------------------------------------

2.獲取超鏈接<a href=..></a>之間內(nèi)容

通常在使用正則表達式時,需要分析網(wǎng)頁鏈接,獲取URL或網(wǎng)頁內(nèi)容。核心代碼如下:
        res = r'<a .*?>(.*?)</a>'
        mm =  re.findall(res, content, re.S|re.M)
        urls=re.findall(r"<a.*?href=.*?<\/a>", content, re.I|re.S|re.M)
例子:

[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3.   
  4. content = ''''' 
  5. <td> 
  6. <a   
  7. link = re.findall(res_url ,  content, re.I|re.S|re.M)  
  8. for url in link:  
  9.     print url  

輸出如下圖所示:

[python] view plain copy
  1. >>>   
  2. 獲取鏈接文本內(nèi)容:  
  3. 浙江省主題介紹  
  4. 貴州省主題介紹  
  5.   
  6. 獲取完整鏈接內(nèi)容:  
  7. <a >貴州省主題介紹</a>  
  8.   
  9. 獲取鏈接中URL:  
  10. https://www.baidu.com/articles/zj.html  
  11. https://www.baidu.com//articles/gz.html  
  12. >>>   

當然如果是通過Selenium分析DOM樹結(jié)構(gòu)獲取href對應(yīng)的url或title中的值,其核心代碼如下所示,這里主要是給大家做個對比,理解不同方法的優(yōu)勢:
      driver.get(link) 
      elem = driver.find_elements_by_xpath("http://div[@class='piclist']/tr/dd[1]")   
      for url in elem:    
            pic_url = url.get_attribute("href")    
            print pic_url
參考文章:[python爬蟲] Selenium定向爬取虎撲籃球海量精美圖片

 

------------------------------------------------------------------------------------------------------------------------------

3.獲取URL最后一個參數(shù)命名圖片或傳遞參數(shù)

通常在使用Python爬取圖片過程中,會遇到圖片對應(yīng)的URL最后一個字段通常用于命名圖片,如虎撲孫悅妻子圖片:
        
  1. urls = "http://i1.hoopchina.com.cn/blogfile/201411/11/BbsImg141568417848931_640*640.jpg"  
  2. values = urls.split('/')[-1]  
  3. print values  
輸出如下所示:
[python] view plain copy
  1. >>>   
  2. BbsImg141568417848931_640*640.jpg  
  3. >>>   
在使用Python獲取GET方法的URL鏈接中,還可能存在傳遞參數(shù)的值。
此時獲取參數(shù)方法如下:
[python] view plain copy
  1. url = 'http://localhost/test.py?a=hello&b=world'    
  2. values = url.split('?')[-1]    
  3. print values    
  4. for key_value in values.split('&'):  
  5.     print key_value.split('=')   
輸出如下所示:
[python] view plain copy
  1. >>>   
  2. a=hello&b=world  
  3. ['a', 'hello']  
  4. ['b', 'world']  
  5. >>>   

------------------------------------------------------------------------------------------------------------------------------

4.爬取網(wǎng)頁中所有URL鏈接

在學習爬蟲過程中,你肯定需要從固有網(wǎng)頁中爬取URL鏈接,再進行下一步的循環(huán)爬取或URL抓取。如下,爬取CSDN首頁的所有URL鏈接。
[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3. import urllib  
  4.   
  5. url = "http://www.csdn.net/"  
  6. content = urllib.urlopen(url).read()  
  7. urls = re.findall(r"<a.*?href=.*?<\/a>", content, re.I)  
  8. for url in urls:  
  9.     print unicode(url,'utf-8')  
  10.       
  11. link_list = re.findall(r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')", content)  
  12. for url in link_list:    
  13.     print url   
輸出如下所示:
[python] view plain copy
  1. >>>   
  2. <a >幫助</a>  
  3. ...  
  4. https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn  
  5. http://passport.csdn.net/account/mobileregister?action=mobileRegister  
  6. https://passport.csdn.net/help/faq  
  7. ...  
  8. >>>  

------------------------------------------------------------------------------------------------------------------------------

5.爬取網(wǎng)頁標題title兩種方法

獲取網(wǎng)頁標題也是一種常見的爬蟲,如我在爬取維基百科國家信息時,就需要爬取網(wǎng)頁title。通常位于<html><head><title>標題</title></head></html>中。
下面是爬取CSDN標題的兩種方法介紹:
[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3. import urllib  
  4.   
  5. url = "http://www.csdn.net/"  
  6. content = urllib.urlopen(url).read()  
  7.   
  8. print u'方法一:'  
  9. title_pat = r'(?<=<title>).*?(?=</title>)'    
  10. title_ex = re.compile(title_pat,re.M|re.S)    
  11. title_obj = re.search(title_ex, content)  
  12. title = title_obj.group()  
  13. print title  
  14.   
  15. print u'方法二:'  
  16. title = re.findall(r'<title>(.*?)</title>', content)  
  17. print title[0]  
輸出如下所示:
[python] view plain copy
  1. >>>   
  2. 方法一:  
  3. CSDN.NET - 全球最大中文IT社區(qū),為IT專業(yè)技術(shù)人員提供最全面的信息傳播和服務(wù)平臺  
  4. 方法二:  
  5. CSDN.NET - 全球最大中文IT社區(qū),為IT專業(yè)技術(shù)人員提供最全面的信息傳播和服務(wù)平臺  
  6. >>>   


------------------------------------------------------------------------------------------------------------------------------

6.定位table位置并爬取屬性-屬性值

如果使用Python庫的一些爬取,通??梢酝ㄟ^DOM樹結(jié)構(gòu)進行定位,如代碼:
    login = driver.find_element_by_xpath("http://form[@id='loginForm']") 
參考文章:[Python爬蟲] Selenium實現(xiàn)自動登錄163郵箱和Locating Elements介紹

但如果是正則表達式這種相對傳統(tǒng)傻瓜式的方法,通過通過find函數(shù)尋找指定table方法進行定位。如:獲取Infobox的table信息。
通過分析源代碼發(fā)現(xiàn)“程序設(shè)計語言列表”的消息盒如下:
<table class="infobox vevent" ..><tr><th></th><td></td></tr></table>
[python] view plain copy
  1. start = content.find(r'<table class="infobox vevent"') #起點記錄查詢位置    
  2. end = content.find(r'</table>')        
  3. infobox = language[start:end]    
  4. print infobox   
print infobox 輸出其中一門語言ActionScript的InfoBox消息盒部分源代碼如下:
[html] view plain copy
  1. <table class="infobox vevent" cellspacing="3" style="border-spacing:3px;width:22em;text-align:left;font-size:small;line-height:1.5em;">     
  2. <caption class="summary"><b>ActionScript</b></caption>     
  3. <tr>     
  4. <th scope="row" style="text-align:left;white-space:nowrap;;;">發(fā)行時間</th>     
  5. <td style=";;">1998年</td>     
  6. </tr>     
  7. <tr>     
  8. <th scope="row" style="text-align:left;white-space:nowrap;;;">實現(xiàn)者</th>     
  9. <td class="organiser" style=";;"><a href="/wiki/Adobe_Systems" title="Adobe Systems">Adobe Systems</a></td>     
  10. </tr>     
  11. <tr>     
  12. <tr>     
  13. <th scope="row" style="text-align:left;white-space:nowrap;;;">啟發(fā)語言</th>     
  14. <td style=";;"><a href="/wiki/JavaScript" title="JavaScript">JavaScript</a>、<a href="/wiki/Java" title="Java">Java</a></td>     
  15. </tr>     
  16. </table>    
參考文章:[python學習] 簡單爬取維基百科程序語言消息盒
然后再在這個infobox內(nèi)容中通過正則表達式進行分析爬取。下面講述爬取屬性-屬性值:
爬取格式如下:
        <table>
                <tr>
                      <th>屬性</th>
                      <td>屬性值</td>
                </tr>
        </table>
其中th表示加粗處理,td和th中可能存在屬性如title、id、type等值;同時<td></td>之間的內(nèi)容可能存在<a href=..></a>或<span></span>或<br />等值,都需要處理。下面先講解正則表達式獲取td值的例子:
參考:http://bbs.csdn.net/topics/390353859?page=1
[html] view plain copy
  1. <table>    
  2. <tr>    
  3. <td>序列號</td><td>DEIN3-39CD3-2093J3</td>    
  4. <td>日期</td><td>2013年1月22日</td>    
  5. <td>售價</td><td>392.70 元</td>    
  6. <td>說明</td><td>僅限5用戶使用</td>    
  7. </tr>    
  8. </table>    
Python代碼如下:
[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3.   
  4. s = '''''<table>   
  5. <tr>   
  6. <td>序列號</td><td>DEIN3-39CD3-2093J3</td>   
  7. <td>日期</td><td>2013年1月22日</td>   
  8. <td>售價</td><td>392.70 元</td>   
  9. <td>說明</td><td>僅限5用戶使用</td>   
  10. </tr>   
  11. </table> 
  12. '''   
  13.   
  14. res = r'<td>(.*?)</td><td>(.*?)</td>'    
  15. m = re.findall(res,s,re.S|re.M)    
  16. for line in m:    
  17.     print unicode(line[0],'utf-8'),unicode(line[1],'utf-8') #unicode防止亂碼    
  18.     
  19. #輸出結(jié)果如下:    
  20. #序列號 DEIN3-39CD3-2093J3    
  21. #日期 2013年1月22日    
  22. #售價 392.70 元    
  23. #說明 僅限5用戶使用   
如果<td id="">包含該屬性則正則表達式為r'<td id=.*?>(.*?)</td>';同樣如果不一定是id屬性開頭,則可以使用正則表達式r'<td .*?>(.*?)</td>'。


------------------------------------------------------------------------------------------------------------------------------

7.過濾<span></span>等標簽

在獲取值過程中,通常會存在<span>、<br>、<a href>等標簽,下面舉個例子過濾。
<td><span class="nickname">(字) 翔宇</span></td>過濾標簽<span>核心代碼:
    elif "span" in nn: #處理標簽<span>
            res_value = r'<span .*?>(.*?)</span>'
            m_value = re.findall(res_value,nn,re.S|re.M) 
            for value in m_value:
                print unicode(value,'utf-8'),
代碼如下,注意print中逗號連接字符串:
[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3.   
  4. language = ''''' 
  5. <table class="infobox bordered vcard" style="width: 21em; font-size: 89%; text-align: left;" cellpadding="3"> 
  6. <caption style="text-align: center; font-size: larger;" class="fn"><b>周恩來</b></caption> 
  7. <tr> 
  8. <th>性別:</th> 
  9. <td>男</td>d 
  10. </tr> 
  11. <tr> 
  12. <th>異名:</th> 
  13. <td><span class="nickname">(字) 翔宇</span></td> 
  14. </tr> 
  15. <tr> 
  16. <th>政黨:</th> 
  17. <td><span class="org"><a href="../articles/%E4%B8%AD9A.html" title="中國">中國</a></span></td> 
  18. </tr> 
  19. <tr> 
  20. <th>籍貫:</th> 
  21. <td><a href="../articles/%E6%B5%9981.html" title="浙江省">浙江省</a><a href="../articles/%E7%BB%8D82.html" title="紹興市">紹興市</a></td> 
  22. </tr> 
  23. </table> 
  24. '''   
  25.   
  26. #獲取table中tr值  
  27. res_tr = r'<tr>(.*?)</tr>'  
  28. m_tr =  re.findall(res_tr,language,re.S|re.M)  
  29. for line in m_tr:  
  30.     #獲取表格第一列th 屬性  
  31.     res_th = r'<th>(.*?)</th>'     
  32.     m_th = re.findall(res_th,line,re.S|re.M)  
  33.     for mm in m_th:  
  34.         if "href" in mm: #如果獲取加粗的th中含超鏈接則處理  
  35.             restr = r'<a href=.*?>(.*?)</a>'  
  36.             h = re.findall(restr,mm,re.S|re.M)  
  37.             print unicode(h[0],'utf-8'), #逗號連接屬性值 防止換行  
  38.         else:  
  39.             print unicode(mm,'utf-8'),   #unicode防止亂  
  40.   
  41.     #獲取表格第二列td 屬性值  
  42.     res_td = r'<td>(.*?)</td>'  #r'<td .*?>(.*?)</td>'  
  43.     m_td = re.findall(res_td,line,re.S|re.M)  
  44.     for nn in m_td:  
  45.         if "href" in nn: #處理超鏈接<a href=../rel=..></a>  
  46.             res_value = r'<a .*?>(.*?)</a>'  
  47.             m_value = re.findall(res_value,nn,re.S|re.M)  
  48.             for value in m_value:  
  49.                 print unicode(value,'utf-8'),  
  50.         elif "span" in nn: #處理標簽<span>  
  51.             res_value = r'<span .*?>(.*?)</span>'  
  52.             m_value = re.findall(res_value,nn,re.S|re.M) #<td><span class="nickname">(字) 翔宇</span></td>  
  53.             for value in m_value:  
  54.                 print unicode(value,'utf-8'),  
  55.         else:  
  56.             print unicode(nn,'utf-8'),  
  57.         print ' ' #換行  
輸出如下所示:
[python] view plain copy
  1. >>>   
  2. 性別: 男    
  3. 異名: (字) 翔宇    
  4. 政黨: 中國
  5. 籍貫: 浙江省 紹興市    
  6. >>>   



------------------------------------------------------------------------------------------------------------------------------

8.獲取<script></script>等標簽內(nèi)容

比如在獲取游訊網(wǎng)圖庫中,圖集對應(yīng)的原圖它是存儲在script中,其中獲取原圖-original即可,縮略圖-thumb,大圖-big,通過正則表達式下載URL:
        res_original = r'"original":"(.*?)"' #原圖
        m_original = re.findall(res_original,script)
代碼如下:
[python] view plain copy
  1. # coding=utf-8  
  2. import re  
  3. import os   
  4.   
  5. content = ''''' 
  6. <script>var images = [   
  7. { "big":"http://i-2.yxdown.com/2015/3/18/KDkwMHgp/6381ccc0-ed65-4422-8671-b3158d6ad23e.jpg",   
  8.   "thumb":"http://i-2.yxdown.com/2015/3/18/KHgxMjAp/6381ccc0-ed65-4422-8671-b3158d6ad23e.jpg",   
  9.   "original":"http://i-2.yxdown.com/2015/3/18/6381ccc0-ed65-4422-8671-b3158d6ad23e.jpg",   
  10.   "title":"","descript":"","id":75109},   
  11. { "big":"http://i-2.yxdown.com/2015/3/18/KDkwMHgp/fec26de9-8727-424a-b272-f2827669a320.jpg",   
  12.   "thumb":"http://i-2.yxdown.com/2015/3/18/KHgxMjAp/fec26de9-8727-424a-b272-f2827669a320.jpg",   
  13.   "original":"http://i-2.yxdown.com/2015/3/18/fec26de9-8727-424a-b272-f2827669a320.jpg",   
  14.   "title":"","descript":"","id":75110},    
  15. </script>   
  16. '''   
  17.   
  18. html_script = r'<script>(.*?)</script>'    
  19. m_script = re.findall(html_script,content,re.S|re.M)    
  20. for script in m_script:  
  21.     res_original = r'"original":"(.*?)"' #原圖  
  22.     m_original = re.findall(res_original,script)  
  23.     for pic_url in m_original:  
  24.         print pic_url  
  25.         filename = os.path.basename(pic_url) #去掉目錄路徑,返回文件名  
  26.         urllib.urlretrieve(pic_url, 'E:\\'+filename) #下載圖片  
運行結(jié)果如下圖所示,同時下載圖片至E盤。
參考文章: [python學習] 簡單爬取圖片網(wǎng)站圖庫中圖片



------------------------------------------------------------------------------------------------------------------------------

9.通過replace過濾<br />標簽

在獲取值過程中,通常會存<br />標簽,它表示HTML換行的意思。常用的方法可以通過標簽'<'和'>'進行過濾,但是這里我想講述的是一種Python常用的過濾方法,在處理中文亂碼或一些特殊字符時,可以使用函數(shù)replace過濾掉這些字符。核心代碼如下:
    if '<br />' in value:
        value = value.replace('<br />','')   #過濾該標簽
        value = value.replace('\n',' ')         #換行空格替代 否則總換行
例如過濾前后的例子:
達洪阿 異名: (字) 厚菴<br /> (諡) 武壯<br /> (勇號) 阿克達春巴圖魯
達洪阿 異名: (字) 厚菴 (諡) 武壯 (勇號) 阿克達春巴圖魯


------------------------------------------------------------------------------------------------------------------------------

10.獲取<img ../>中超鏈接及過濾<img>標簽

在獲取值屬性值過程中,可能在分析table/tr/th/td標簽后,仍然存在<img />圖片鏈接,此時在獲取文字內(nèi)容時,你可能需要過濾掉這些<img>標簽。這里采用的方法如下:
        value = re.sub('<[^>]+>','', value)
例如:
[python] view plain copy
  1. #encoding:utf-8  
  2. import os  
  3. import re  
  4.   
  5. value = ''''' 
  6. <table class="infobox" style="width: 21em; text-align: left;" cellpadding="3"> 
  7. <tr bgcolor="#CDDBE8"> 
  8. <th colspan="2"> 
  9. <center class="role"><b>中華民國政治人士</b><br /></center> 
  10. </th> 
  11. </tr> 
  12. <tr> 
  13. <th>性別:</th> 
  14. <td>男</td> 
  15. </tr> 
  16. <tr> 
  17. <th>政黨:</th> 
  18. <td><span class="org"> 
  19. <img alt="中國國民黨" src="../../../../images/Kuomintang.svg.png" width="19" height="19" border="0" /> 
  20. <a href="../../../../articles/%8B%E6%B0%91%E9%BB%A8.html" title="中國國民黨">中國國民黨</a></span></td> 
  21. </tr> 
  22. </table> 
  23. '''  
  24.   
  25. value = re.sub('<[^>]+>','', value) #過濾HTML標簽  
  26. print value  
輸出如下:
[python] view plain copy
  1. >>>   
  2.   
  3. 中華民國政治人士  
  4.   
  5. 性別:  
  6. 男  
  7.   
  8. 政黨:  
  9.   
  10. 中國國民黨  
  11.   
  12. >>>   
雖然僅僅包括漢字,但是中間會存在換行,需要過濾<br />即可:
[python] view plain copy
  1. if '<br />' in value:  
  2.     value = value.replace('<br />','')  
  3.     value = value.replace('\n',' ')  
  4. value = re.sub('<[^>]+>','', value) #過濾HTML標簽  
  5. print value  
  6.   
  7. #輸出僅僅一行如下:   
  8. #中華民國政治人士    性別: 男   政黨:   中國國民黨      
下面講述第二部分,通過正則表達式獲取<img>中的src超鏈接,代碼如下:
[python] view plain copy
  1. test = '''''<img alt="中國國民黨" src="../images/Kuomintang.png" width="19" height="19" border="0" />'''  
  2. print re.findall('src="(.*?)"',test)  
輸出如下所示:
[python] view plain copy
  1. >>>      
  2. ['../images/Kuomintang.png']  
  3. >>>   
findall函數(shù)返回的總是正則表達式在字符串中所有匹配結(jié)果的列表,即findall中返回列表中每個元素包含的信息。
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Python爬蟲常用正則表達式及HTML網(wǎng)頁標簽分析總結(jié)
python 正則表達式re findall
Python爬蟲筆記:爬取單個頁面
[Python從零到壹] 四.網(wǎng)絡(luò)爬蟲之入門基礎(chǔ)及正則表達式抓取博客案例
表格標簽-三行三列
HTML <table> 標簽
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服