本文將舉例說明抓取網頁數據的三種方式:正則表達式、BeautifulSoup、lxml。
利用該代碼獲取抓取整個網頁。css
import requests def download(url, num_retries=2, user_agent='wswp', proxies=None): '''下載一個指定的URL並返回網頁內容 參數: url(str): URL 關鍵字參數: user_agent(str):用戶代理(默認值:wswp) proxies(dict): 代理(字典): 鍵:‘http’'https' 值:字符串(‘http(s)://IP’) num_retries(int):若是有5xx錯誤就重試(默認:2) #5xx服務器錯誤,表示服務器沒法完成明顯有效的請求。 #https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81 ''' print('==========================================') print('Downloading:', url) headers = {'User-Agent': user_agent} #頭部設置,默認頭部有時候會被網頁反扒而出錯 try: resp = requests.get(url, headers=headers, proxies=proxies) #簡單粗暴,.get(url) html = resp.text #獲取網頁內容,字符串形式 if resp.status_code >= 400: #異常處理,4xx客戶端錯誤 返回None print('Download error:', resp.text) html = None if num_retries and 500 <= resp.status_code < 600: # 5類錯誤 return download(url, num_retries - 1)#若是有服務器錯誤就重試兩次 except requests.exceptions.RequestException as e: #其餘錯誤,正常報錯 print('Download error:', e) html = None return html #返回html
爬取http://example.webscraping.com/places/default/view/Australia-14網頁中全部顯示內容。html
網頁結構python
分析網頁結構能夠看出,全部內容都在標籤<table>中,以area爲例能夠看出,area的值在:
<tr id="places_area__row"><td class="w2p_fw">7,686,850 square kilometres</td>
根據這個結構,咱們用不一樣的方式來表達,就能夠抓取到全部想要的數據了。web
#正則表達式: re.search(r'<tr id="places_area__row">.*?<td class="w2p_fw">(.*?)</td>').groups()[0] # .*?表示任意非換行值,()是分組,可用於輸出。 #BeautifulSoup soup.find('table').find('tr', id='places_area__row').find('td', class_="w2p_fw").text #lxml_css selector tree.cssselect('table > tr#places_area__row > td.w2p_fw' )[0].text_content() #lxml_xpath tree.xpath('//tr[@id="places_area__row"]/td[@class="w2p_fw"]' )[0].text_content()
Chrome 瀏覽器能夠方便的複製出各類表達方式:正則表達式
複製格式api
有了以上的download函數和不一樣的表達式,咱們就能夠用三種不一樣的方法來抓取數據了。瀏覽器
正則表達式無論在python仍是其餘語言都有很好的應用,用簡單的規定符號來表達不一樣的字符串組成形式,簡潔又高效。學習正則表達式頗有必要。 python內置正則表達式,無需額外安裝。服務器
import re targets = ('area', 'population', 'iso', 'country', 'capital', 'continent', 'tld', 'currency_code', 'currency_name', 'phone', 'postal_code_format', 'postal_code_regex', 'languages', 'neighbours') def re_scraper(html): results = {} for target in targets: results[target] = re.search(r'<tr id="places_%s__row">.*?<td class="w2p_fw">(.*?)</td>' % target, html).groups()[0] return results
代碼以下:函數
from bs4 import BeautifulSoup targets = ('area', 'population', 'iso', 'country', 'capital', 'continent', 'tld', 'currency_code', 'currency_name', 'phone', 'postal_code_format', 'postal_code_regex', 'languages', 'neighbours') def bs_scraper(html): soup = BeautifulSoup(html, 'html.parser') results = {} for target in targets: results[target] = soup.find('table').find('tr', id='places_%s__row' % target) \ .find('td', class_="w2p_fw").text return results
from lxml.html import fromstring def lxml_scraper(html): tree = fromstring(html) results = {} for target in targets: results[target] = tree.cssselect('table > tr#places_%s__row > td.w2p_fw' % target)[0].text_content() return results def lxml_xpath_scraper(html): tree = fromstring(html) results = {} for target in targets: results[target] = tree.xpath('//tr[@id="places_%s__row"]/td[@class="w2p_fw"]' % target)[0].text_content() return results
scrapers = [('re', re_scraper), ('bs',bs_scraper), ('lxml', lxml_scraper), ('lxml_xpath',lxml_xpath_scraper)] html = download('http://example.webscraping.com/places/default/view/Australia-14') for name, scraper in scrapers: print(name,"=================================================================") result = scraper(html) print(result)
========================================== Downloading: http://example.webscraping.com/places/default/view/Australia-14 re ================================================================= {'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': '<a href="/places/default/continent/OC">OC</a>', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': '<div><a href="/places/default/iso//"> </a></div>'} bs ================================================================= {'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': 'OC', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': ' '} lxml ================================================================= {'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': 'OC', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': ' '} lxml_xpath ================================================================= {'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': 'OC', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': ' '}
從結果能夠看出正則表達式在某些地方返回多餘元素,而不是純粹的文本。這是由於這些地方的網頁結構和別的地方不一樣,所以正則表達式不能徹底覆蓋同樣的內容,若有的地方包含連接和圖片。而BeautifulSoup和lxml有專門的提取文本函數,所以不會有相似錯誤。post
既然有三種不一樣的抓取方式,那有什麼區別?應用場合如何?該如何選擇呢? ···to be continued···