Python網頁解析器使用實例詳解
python 網頁解析器
1、常見的python網頁解析工具有:re正則匹配、python自帶的html.parser模塊、第三方庫BeautifulSoup(重點學習)以及lxm庫。
2、常見網頁解析器分類
(1)模糊匹配 :re正則表達式即為字符串式的模糊匹配模式;
(2)結構化解析: BeatufiulSoup、html.parser與lxml,他們都以DOM樹結構為標準,進行標簽結構信息的提取。
3.DOM樹解釋:即文檔對象模型(Document Object Model),其樹形標簽結構,請見下圖。
所謂結構化解析,就是網頁解析器它會將下載的整個HTML文檔當成一個Doucment對象,然后在利用其上下結構的標簽形式,對這個對象進行上下級的標簽進行遍歷和信息提取操作。
# 引入相關的包,urllib與bs4,是獲取和解析網頁最常用的庫from urllib.request import urlopenfrom bs4 import BeautifulSoup# 打開鏈接html=urlopen('https://www.datalearner.com/website_navi')# 通過urlopen獲得網頁對象,將其放入BeautifulSoup中,bsObj存放的目標網頁的html文檔bsObj=BeautifulSoup(html.read())print(bsObj)
# soup = BeautifulSoup(open(url,’r’,encoding = ’utf-8’))
import requestsfrom bs4 import BeautifulSoupheaders={’User-Agent’: ’Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36’,’referer’:'www.mmjpg.com' }all_url = ’http://www.mmjpg.com/’ #’User-Agent’:請求方式 #’referer’:從哪個鏈接跳轉進來的start_html = requests.get(all_url, headers=headers) #all_url:起始的地址,也就是訪問的第一個頁面 #headers:請求頭,告訴服務器是誰來了。 #requests.get:一個方法能獲取all_url的頁面內容并且返回內容。Soup = BeautifulSoup(start_html.text, ’lxml’) #BeautifulSoup:解析頁面 #lxml:解析器 #start_html.text:頁面的內容
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: