十分钟能学会的简单python爬虫
簡單爬蟲三步走,So easy~
本文介紹一個使用python實現爬蟲的超簡單方法,精通爬蟲挺難,但學會實現一個能滿足簡單需求的爬蟲,只需10分鐘,往下讀吧~
該方法不能用于帶有反爬機制的頁面,但對于我這樣的非專業爬蟲使用者,幾乎遇到的各種簡單爬蟲需求都是可以搞定的。
歸納起來,只有簡單的3步
- 使用開發人員工具分析網頁HTML
- 請求網頁
- 獲取相應信息
我們以一個簡單的需求為例:
從wiki百科標普500指數頁面中,利用爬蟲自動獲取 S&P 500指數所對應的所有股票。如圖所示:
第一步:使用開發人員工具分析網頁HTML
首先我們要對待爬取的網頁人工的進行結構分析
這里我使用的是Google瀏覽器
進入頁面后,按下F12,打開開發人員工具
選擇開發人員工具左上角的小箭頭
這是一個映射工具
通過它你可以輕松的觀察網頁中每一個渲染后的元素所對應于網頁HTML中的位置
這能夠幫我們很輕松的完成html的結構分析,從而快速實現一個爬蟲
就像這樣
通過觀察,我們發現,所有待爬取的股票信息都位于一個表格中
這個表格對應于一個<table class="wikitable sortable jquery-tablesorter"> 標簽
而表格中每一行的的股票信息又對應了table 下的一個tr 標簽
因此我們爬蟲的工作就是get到table 下的所有tr 標簽,并解析出相應內容
第一步網頁HTML分析,完成!
第二步:請求網頁
下面開始進入代碼階段
這里我使用的是Python3
需要用到requests 和 BeautifulSoup 這兩個庫
因此別忘記引用:
首先我們需要請求網頁:
response = requests.get("http://en.wikipedia.org/wiki/List_of_S%26P_500_companies")隨后使用BeautifulSoup解析
soup = bs4.BeautifulSoup(response.text,"html5lib")沒有錯,就是這么簡單~
第三步:獲取相應信息
結合第一步的分析
我們爬蟲的工作就是get到table 下的所有tr 標簽,并解析出相應內容
通過BeautifulSoup庫的一個核心的方法select 我們便能完成這個工作
首先獲取所有的tr 標簽
然后獲取tr 標簽中所需的屬性并打印出來
symbols = [] for i, symbol in enumerate(symbolslist):tds = symbol.select('td')symbols.append((tds[0].select('a')[0].text, # Tickertds[1].select('a')[0].text, # Nametds[3].text, # Sector))大功告成,最終的程序運行結果如下:
全部代碼如下:
import bs4 import requestsif __name__ == "__main__":"""Download and parse the Wikipedia list of S&P500 constituents using requests and BeautifulSoup.Returns a list of tuples for to add to MySQL."""# Use requests and BeautifulSoup to download the# list of S&P500 companies and obtain the symbol tableresponse = requests.get("http://en.wikipedia.org/wiki/List_of_S%26P_500_companies")soup = bs4.BeautifulSoup(response.text,"html5lib")# This selects the first table, using CSS Selector syntax# and then ignores the header row ([1:])symbolslist = soup.select('table')[0].select('tr')[1:]# Obtain the symbol information for each# row in the S&P500 constituent tablesymbols = []for i, symbol in enumerate(symbolslist):tds = symbol.select('td')symbols.append((tds[0].select('a')[0].text, # Tickertds[1].select('a')[0].text, # Nametds[3].text, # Sector))# show the symbolsshowNum =10for i in range(showNum):print(symbols[i])總結
以上是生活随笔為你收集整理的十分钟能学会的简单python爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql safe file priv
- 下一篇: PID控制器改进笔记之四:改进PID控制