Python 爬蟲入門實例(爬取小米應用商店的top應用apk)


一,爬蟲是什么?

爬蟲就是獲取網絡上各種資源,數據的一種工具。具體的可以自行百度。

二,如何寫簡單爬蟲

1,獲取網頁內容

可以通過 Python(3.x) 自帶的 urllib,來實現網頁內容的下載。實現起來很簡單

import urllib.request

url="http://www.baidu.com"
response=urllib.request.urlopen(url)
html_content=response.read()

 還可以使用三方庫 requests ,實現起來也非常方便,在使用之前當然你需要先安裝這個庫:pip install requests 即可(Python 3以后的pip非常好使)

 

import requests

html_content=requests.get(url).text

2, 解析網頁內容

獲取的網頁內容html_content,其實就是html代碼,我們需要對其進行解析,獲取我們所需要的內容。

解析網頁的方法有很多,這里我介紹的是BeautifullSoup,由於這是一個三方庫,在使用前 還是要先安裝 :pip install bs4

form bs4 imort BeautifullSoup

soup= BeautifullSoup(html_content, "html.parser")

更多使用方法請參考官方文檔:http://beautifulsoup.readthedocs.io/zh_CN/latest/

三,實例分析

弄懂爬蟲原理的最好辦法,就是多分析一些實例,爬蟲千變萬化,萬變不離其宗。廢話少說上干貨。

===================================我是分割線===================================================

需求:爬取小米應用商店的TOP n 應用

通過瀏覽器打開小米應用商店排行棒頁面,F12審查元素

 

#coding=utf-8
import requests
import re
from bs4 import BeautifullSoup def parser_apks(self, count=0): '''小米應用市場''' _root_url="http://app.mi.com" #應用市場主頁網址 res_parser={} page_num=1 #設置爬取的頁面,從第一頁開始爬取,第一頁爬完爬取第二頁,以此類推 while count:
#獲取排行榜頁面的網頁內容 wbdata
= requests.get("http://app.mi.com/topList?page="+str(page_num)).text print("開始爬取第"+str(page_num)+"")
#解析頁面內容獲取 應用下載的 界面連接 soup
=BeautifulSoup(wbdata,"html.parser") links=soup.body.contents[3].find_all("a",href=re.compile("/details?"), class_ ="", alt="") #BeautifullSoup的具體用法請百度一下吧。。。 for link in links: detail_link=urllib.parse.urljoin(_root_url, str(link["href"])) package_name=detail_link.split("=")[1]
#在下載頁面中獲取 apk下載的地址 download_page
=requests.get(detail_link).text soup1=BeautifulSoup(download_page,"html.parser") download_link=soup1.find(class_="download")["href"] download_url=urllib.parse.urljoin(_root_url, str(download_link))
#解析后會有重復的結果,下面通過判斷去重
if download_url not in res_parser.values(): res_parser[package_name]=download_url count=count-1 if count==0: break if count >0: page_num=page_num+1 print("爬取apk數量為: "+str(len(res_parser))) return res_parser
def craw_apks(self, count=1, save_path="d:\\apk\\"):
        res_dic=parser_apks(count) for apk in res_dic.keys(): print("正在下載應用: "+apk) urllib.request.urlretrieve(res_dic[apk],save_path+apk+".apk") print("下載完成")
if __name__=="__main__":

craw_apks(10)

運行結果:

開始爬取第1頁
爬取apk數量為: 10
正在下載應用: com.tencent.tmgp.sgame
下載完成
.
.
.

以上就是簡單爬蟲的內容,其實爬蟲的實現還是很復雜的,不同的網頁有不同的解析方式,還需要深入學習。。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM