參考網址:http://blog.csdn.net/Eastmount/article/details/51082253
常用正則表達式爬取網頁信息及HTML分析總結
1.獲取<tr></tr>標簽之間內容
2.獲取<a href..></a>超鏈接之間內容
3.獲取URL最后一個參數命名圖片或傳遞參數
4.爬取網頁中所有URL鏈接
5.爬取網頁標題title兩種方法
6.定位table位置並爬取屬性-屬性值
7.過濾<span></span>等標簽
8.獲取<script></script>等標簽內容
9.通過replace函數過濾<br />標簽
10.獲取<img ../>中超鏈接及過濾<img>標簽
1.獲取<tr></tr>標簽之間內容
該部分主要是通過正則表達式獲取兩個標簽之間的內容,通常這種標簽都是成對出現的。
開始標簽如:<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)
例子:
import re
language = ''''<tr><th>性別:</th><td>男</td></tr>'''
# 正則表達式獲取<tr></tr>之間內容
res_tr = r'<tr>(.*?)</tr>'
m_tr = re.findall(res_tr, language, re.S | re.M)
for line in m_tr:
print line
# 獲取表格第一列th 屬性
res_th = r'<th>(.*?)</th>'
m_th = re.findall(res_th, line, re.S | re.M)
for mm in m_th:
print unicode(mm, 'utf-8'), # unicode防止亂
# 獲取表格第二列td 屬性值
res_td = r'<td>(.*?)</td>'
m_td = re.findall(res_td, line, re.S | re.M)
for nn in m_td:
print unicode(nn, 'utf-8')
輸出結果:
2.獲取超鏈接<a href=..></a>之間內容
通常在使用正則表達式時,需要分析網頁鏈接,獲取URL或網頁內容。核心代碼如下:
res = r'<a .*?>(.*?)</a>'
mm = re.findall(res, content, re.S|re.M)
res_url=r'href="(.*?)"'
例子:
content = '''''
<td>
<a href="https://www.baidu.com/articles/zj.html" title="浙江省">浙江省主題介紹</a>
<a href="https://www.baidu.com//articles/gz.html" title="貴州省">貴州省主題介紹</a>
</td>
'''
# 獲取<a href></a>之間的內容
print u'獲取鏈接文本內容:'
res = r'<a .*?>(.*?)</a>'
mm = re.findall(res, content, re.S | re.M)
for value in mm:
print value
# 獲取所有<a href></a>鏈接所有內容
print u'\n獲取完整鏈接內容:'
urls = re.findall(r"<a.*?href=.*?</a>", content, re.I | re.S | re.M)
for i in urls:
print i
# 獲取<a href></a>中的URL
print u'\n獲取鏈接中URL:'
#res_url = r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')" 此代碼是沒有讀懂,下面換了一種寫法
res_url=r'href="(.*?)"'
link = re.findall(res_url, content, re.I | re.S | re.M)
for url in link:
print url
輸出結果: