零基礎入門Python,給本身找了一個任務,作網站文章的爬蟲小項目,由於實戰是學代碼的最快方式。因此從今天起開始寫Python實戰入門系列教程,也建議你們學Python時必定要多寫多練。html
項目用的BeautifulSoup4和chardet模塊屬於三方擴展包,若是沒有請自行pip安裝,我是用pycharm來作的安裝,下面簡單講下用pycharm安裝chardet和BeautifulSoup4html5
在pycharm的設置裏按照下圖的步驟操做 正則表達式
以下圖搜索你要的擴展類庫,如咱們這裏須要安裝chardet直接搜索就行,而後點擊install package, BeautifulSoup4作同樣的操做就行數據庫
咱們這裏以抓取簡書首頁爲例:www.jianshu.com/api
# 簡單的網絡爬蟲
from urllib import request
import chardet
response = request.urlopen("http://www.jianshu.com/")
html = response.read()
charset = chardet.detect(html)# {'language': '', 'encoding': 'utf-8', 'confidence': 0.99}
html = html.decode(str(charset["encoding"])) # 解碼
print(html)
複製代碼
因爲抓取的html文檔比較長,這裏簡單貼出來一部分給你們看下bash
<!DOCTYPE html>
<!--[if IE 6]><html class="ie lt-ie8"><![endif]-->
<!--[if IE 7]><html class="ie lt-ie8"><![endif]-->
<!--[if IE 8]><html class="ie ie8"><![endif]-->
<!--[if IE 9]><html class="ie ie9"><![endif]-->
<!--[if !IE]><!--> <html> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
<!-- Start of Baidu Transcode -->
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta http-equiv="Cache-Control" content="no-transform" />
<meta name="applicable-device" content="pc,mobile">
<meta name="MobileOptimized" content="width"/>
<meta name="HandheldFriendly" content="true"/>
<meta name="mobile-agent" content="format=html5;url=http://localhost/">
<!-- End of Baidu Transcode -->
<meta name="description" content="簡書是一個優質的創做社區,在這裏,你能夠任性地創做,一篇短文、一張照片、一首詩、一幅畫……咱們相信,每一個人都是生活中的藝術家,有着無窮的創造力。">
<meta name="keywords" content="簡書,簡書官網,圖文編輯軟件,簡書下載,圖文創做,創做軟件,原創社區,小說,散文,寫做,閱讀">
..........後面省略一大堆
複製代碼
這就是Python3的爬蟲簡單入門,是否是很簡單,建議你們多敲幾遍網絡
目標app
import re
import urllib.request
#爬取網頁html
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
html = getHtml("http://tieba.baidu.com/p/3205263090")
html = html.decode('UTF-8')
#獲取圖片連接的方法
def getImg(html):
# 利用正則表達式匹配網頁裏的圖片地址
reg = r'src="([.*\S]*\.jpg)" pic_ext="jpeg"'
imgre=re.compile(reg)
imglist=re.findall(imgre,html)
return imglist
imgList=getImg(html)
imgCount=0
#for把獲取到的圖片都下載到本地pic文件夾裏,保存以前先在本地建一個pic文件夾
for imgPath in imgList:
f=open("../pic/"+str(imgCount)+".jpg",'wb')
f.write((urllib.request.urlopen(imgPath)).read())
f.close()
imgCount+=1
print("所有抓取完成")
複製代碼
火燒眉毛的看下都爬取到了些什麼美圖ide
就這麼輕易的爬取到了24個妹子的圖片。是否是很簡單。學習
到這裏稍微複雜點,就分佈給你們講解
這裏就要用到咱們導入的BeautifulSoup4庫了,這裏的關鍵代碼
# 使用剖析器爲html.parser
soup = BeautifulSoup(html, 'html.parser')
# 獲取到每個class=hot-article-img的a節點
allList = soup.select('.hot-article-img')
複製代碼
上面代碼獲取到的allList就是咱們要獲取的新聞列表,抓取到的以下
[<div class="hot-article-img">
<a href="/article/211390.html" target="_blank">
![](https://img.huxiucdn.com/article/cover/201708/22/173535862821.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214982.html" target="_blank" title="TFBOYS成員各自飛,商業價值天花板已現?">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/094856378420.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/213703.html" target="_blank" title="買手店江湖">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/122655034450.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214679.html" target="_blank" title="iPhone X正式告訴咱們,手機和相機開始分道揚鑣">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/14/182151300292.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214962.html" target="_blank" title="信用已被透支殆盡,樂視汽車或成賈躍亭棄子">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/210518696352.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214867.html" target="_blank" title="別小看「搞笑諾貝爾獎」,要向好奇心致敬">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/15/180620783020.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214954.html" target="_blank" title="10 年前改變世界的,可不止有 iPhone | 發車">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/162049096015.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214908.html" target="_blank" title="感謝微博替我作主">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/010410913192.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/215001.html" target="_blank" title="蘋果確認取消打賞抽成,但還有多少內容讓你以爲值得掏腰包?">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/154147105217.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214969.html" target="_blank" title="中國音樂的「全面付費」時代即將到來?">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/101218317953.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214964.html" target="_blank" title="百麗退市啓示錄:「一代鞋王」如何與新生代消費者漸行漸遠">
<!--視頻和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/213400162818.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>]
複製代碼
這裏數據是抓取到了,可是太亂了,而且還有不少不是咱們想要的,下面就經過遍從來提煉出咱們的有效信息
#遍歷列表,獲取有效信息
for news in allList:
aaa = news.select('a')
# 只選擇長度大於0的結果
if len(aaa) > 0:
# 文章連接
try:#若是拋出異常就表明爲空
href = url + aaa[0]['href']
except Exception:
href=''
# 文章圖片url
try:
imgUrl = aaa[0].select('img')[0]['src']
except Exception:
imgUrl=""
# 新聞標題
try:
title = aaa[0]['title']
except Exception:
title = "標題爲空"
print("標題",title,"\nurl:",href,"\n圖片地址:",imgUrl)
print("==============================================================================================")
複製代碼
這裏添加異常處理,主要是有的新聞可能沒有標題,沒有url或者圖片,若是不作異常處理,可能致使咱們爬取的中斷。
標題 標題爲空
url: https://www.huxiu.com/article/211390.html
圖片地址: https://img.huxiucdn.com/article/cover/201708/22/173535862821.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 TFBOYS成員各自飛,商業價值天花板已現?
url: https://www.huxiu.com/article/214982.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/17/094856378420.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 買手店江湖
url: https://www.huxiu.com/article/213703.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/17/122655034450.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 iPhone X正式告訴咱們,手機和相機開始分道揚鑣
url: https://www.huxiu.com/article/214679.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/14/182151300292.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 信用已被透支殆盡,樂視汽車或成賈躍亭棄子
url: https://www.huxiu.com/article/214962.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/16/210518696352.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 別小看「搞笑諾貝爾獎」,要向好奇心致敬
url: https://www.huxiu.com/article/214867.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/15/180620783020.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 10 年前改變世界的,可不止有 iPhone | 發車
url: https://www.huxiu.com/article/214954.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/16/162049096015.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 感謝微博替我作主
url: https://www.huxiu.com/article/214908.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/16/010410913192.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 蘋果確認取消打賞抽成,但還有多少內容讓你以爲值得掏腰包?
url: https://www.huxiu.com/article/215001.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/17/154147105217.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 中國音樂的「全面付費」時代即將到來?
url: https://www.huxiu.com/article/214969.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/17/101218317953.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
標題 百麗退市啓示錄:「一代鞋王」如何與新生代消費者漸行漸遠
url: https://www.huxiu.com/article/214964.html
圖片地址: https://img.huxiucdn.com/article/cover/201709/16/213400162818.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg
==============================================================================================
複製代碼
到這裏咱們抓取新聞網站新聞信息就大功告成了,下面貼出來完整代碼
from bs4 import BeautifulSoup
from urllib import request
import chardet
url = "https://www.huxiu.com"
response = request.urlopen(url)
html = response.read()
charset = chardet.detect(html)
html = html.decode(str(charset["encoding"])) # 設置抓取到的html的編碼方式
# 使用剖析器爲html.parser
soup = BeautifulSoup(html, 'html.parser')
# 獲取到每個class=hot-article-img的a節點
allList = soup.select('.hot-article-img')
#遍歷列表,獲取有效信息
for news in allList:
aaa = news.select('a')
# 只選擇長度大於0的結果
if len(aaa) > 0:
# 文章連接
try:#若是拋出異常就表明爲空
href = url + aaa[0]['href']
except Exception:
href=''
# 文章圖片url
try:
imgUrl = aaa[0].select('img')[0]['src']
except Exception:
imgUrl=""
# 新聞標題
try:
title = aaa[0]['title']
except Exception:
title = "標題爲空"
print("標題",title,"\nurl:",href,"\n圖片地址:",imgUrl)
print("==============================================================================================")
複製代碼
數據獲取到了咱們還要把數據存到數據庫,只要存到咱們的數據庫裏,數據庫裏有數據了,就能夠作後面的數據分析處理,也能夠用這些爬取來的文章,給app提供新聞api接口,固然這都是後話了,等我自學到Python數據庫操做之後,會寫一篇文章 《Python3實戰入門數據庫篇---把爬取到的數據存到數據庫》