019年4月16日零基礎入門Python,第二天就給自己找了一個任務,做網站文章的爬蟲小項目,因為實戰是學代碼的最快方式。所以從今天起開始寫Python實戰入門系列教程,也建議大家學Python時一定要多寫多練。
一,首先看看Python是如何簡單的爬取網頁的
1,準備工作
項目用的BeautifulSoup4和chardet模塊屬于三方擴展包,如果沒有請自行pip安裝,我是用pycharm來做的安裝,下面簡單講下用pycharm安裝chardet和BeautifulSoup4
二,由淺入深,我們先抓取網頁
我們這里以抓取簡書首頁為例:http://www.jianshu.com/
# 簡單的網絡爬蟲 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文檔比較長,這里簡單貼出來一部分給大家看下
<!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的爬蟲簡單入門,是不是很簡單,建議大家多敲幾遍
三,Python3爬取網頁里的圖片并把圖片保存到本地文件夾
目標
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("全部抓取完成")
迫不及待的看下都爬取到了些什么美圖
就這么輕易的爬取到了24個妹子的圖片。是不是很簡單。
四,Python3爬取新聞網站新聞列表
到這里稍微復雜點,就分布給大家講解
分析上圖我們要抓取的信息再div中的a標簽和img標簽里,所以我們要想的就是怎么獲取到這些信息
這里就要用到我們導入的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">  </a> </div>, <div class="hot-article-img"> <a href="/article/214982.html" target="_blank" title="TFBOYS成員各自飛,商業價值天花板已現?"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/213703.html" target="_blank" title="買手店江湖"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214679.html" target="_blank" title="iPhone X正式告訴我們,手機和相機開始分道揚鑣"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214962.html" target="_blank" title="信用已被透支殆盡,樂視汽車或成賈躍亭棄子"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214867.html" target="_blank" title="別小看“搞笑諾貝爾獎”,要向好奇心致敬"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214954.html" target="_blank" title="10 年前改變世界的,可不止有 iPhone | 發車"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214908.html" target="_blank" title="感謝微博替我做主"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/215001.html" target="_blank" title="蘋果確認取消打賞抽成,但還有多少內容讓你覺得值得掏腰包?"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214969.html" target="_blank" title="中國音樂的“全面付費”時代即將到來?"> <!--視頻和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214964.html" target="_blank" title="百麗退市啟示錄:“一代鞋王”如何與新生代消費者漸行漸遠"> <!--視頻和圖片保留一個-->  </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實戰入門數據庫篇---把爬取到的數據存到數據庫》
編程小石頭,為分享干貨而生!據說,每個年輕上進,顏值又高的互聯網人都關注了編程小石頭。
索 HTML 圖像的不同概念,以及如何有效地使用它們在您的網站上增加視覺吸引力、傳達信息和表達情感。 本指南包含大量示例和實用技巧,可幫助您創建一個視覺效果驚人且用戶友好的網站。
圖像是網頁設計師和開發人員的強大工具,它們可用于傳達信息、表達情感并使網站更具視覺吸引力。 HTML 圖像概念是網頁設計和開發的重要方面。 它們用于將圖像嵌入到網頁中,以便于顯示和共享圖片和圖形。 在這篇博文中,我們將探討 HTML 圖像的不同概念以及如何有效地使用它們。
首先,讓我們談談不同類型的 HTML 圖像。 有兩種主要類型的圖像:內嵌圖像和背景圖像。 內聯圖像直接嵌入到 HTML 代碼中,而背景圖像則應用于元素的背景。
在此示例中,內聯圖像“image.jpg”直接嵌入到 HTML 代碼中并顯示給用戶。
在此示例中,背景圖像“image.jpg”應用于 div 元素的背景并顯示給用戶。
以合乎邏輯且一致的方式使用圖像也很重要。 這意味著您應該使用它們來傳達與網頁內容相關的信息或表達情感,而不是隨意使用它們。 此外,使用 alt 屬性為圖像添加文本替代也很重要,它允許可能使用屏幕閱讀器的用戶訪問圖像,或者以防圖像加載失敗。
在此示例中,替代文本“日落的美麗圖像”讓用戶清楚地了解圖像所代表的內容。
另一個 HTML 圖像概念是使用寬度和高度屬性調整圖像大小的能力。 這些屬性允許您調整圖像大小以適合您的布局和設計。
在此示例中,圖像的寬度設置為 300 像素,圖像的高度設置為 200 像素。
HTML 圖像概念是網頁設計和開發的重要方面。 它們用于將圖像嵌入到網頁中,以便于顯示和共享圖片和圖形。 通過了解不同類型的圖像并正確使用它們,您可以為您的網站增加額外的視覺吸引力,并以有力的方式傳達信息或表達情感。 無論是使用內聯圖片還是背景圖片,添加替代文本或調整大小,這些概念都是創建視覺效果驚人且用戶友好的網站的關鍵。
但不要只相信我們的話,您自己試試吧! 嘗試使用 HTML 圖像,看看它們如何增強您網站的整體外觀。 通過每一行代碼,您離創建一個您的訪問者會喜歡的美觀且引人入勝的網站又近了一步。 請記住,圖像具有喚起情感和傳達信息的力量,因此請明智地使用它們并將它們作為您網頁設計策略的重要組成部分。 通過正確組合 HTML 和圖像,您將創建一個脫穎而出并給訪問者留下持久印象的網站。
作者:極客小俊」
「 把邏輯思維轉變為代碼的技術博主」
咱們廢話不多說直接上代碼案例素材!
首先準備圖片素材 放入到你的demo案例下的img文件夾
當然圖片你也可以用其他類似的圖來代替也是可以的!
如圖
<div id="big">
<div class="box">
<div class="pic"><img src="img/bag.jpg" alt="" title=""/></div>
<div class="mask">
<h2>三用小巧思波士頓包</h2>
<p>印花波士頓包 復古波士頓包,手提單肩斜挎多用,印花PVC</p>
</div>
<div class="title">
<h2 class="sl"><span></span>全場2折起 印花波士頓包 專柜終身保養</h2>
<h3 class="sl"><i></i><span>搶全場2件88折</span>新款蜜蜂系列印花手提斜挎包</h3>
<div class="price">
<div class="zx_pr"><span>¥</span>659</div>
<div class="xl_yp">
<p><del>¥1998.00</del><span>退貨賠運費</span></p>
<p><strong>70</strong>件已付款</p>
</div>
<div class="buy">搶!</div>
</div>
</div>
</div>
<div class="box">
<div class="pic"><img src="img/bag3.jpg" alt="" title=""/></div>
<div class="mask">
<h2>豬年紀念款經典牛皮水桶包</h2>
<p>豬年紀念款 經典牛皮水桶包,自帶強大氣場</p>
</div>
<div class="title">
<h2 class="sl"><span></span>全場2折起 印花波士頓包 專柜終身保養</h2>
<h3 class="sl"><i></i><span>搶全場2件88折</span>新款蜜蜂系列印花手提斜挎包</h3>
<div class="price">
<div class="zx_pr"><span>¥</span>659</div>
<div class="xl_yp">
<p><del>¥1998.00</del><span>退貨賠運費</span></p>
<p><strong>70</strong>件已付款</p>
</div>
<div class="buy">搶!</div>
</div>
</div>
</div>
<div class="box">
<div class="pic"><img src="img/bag4.jpg" alt="" title=""/></div>
<div class="mask">
<h2>一包四用蜜蜂系列迷你小方包</h2>
<p>四用方盒包 一包四用蜜蜂系列迷你鏈條小方包</p>
</div>
<div class="title">
<h2 class="sl"><span></span>全場2折起 印花波士頓包 專柜終身保養</h2>
<h3 class="sl"><i></i><span>搶全場2件88折</span>新款蜜蜂系列印花手提斜挎包</h3>
<div class="price">
<div class="zx_pr"><span>¥</span>659</div>
<div class="xl_yp">
<p><del>¥1998.00</del><span>退貨賠運費</span></p>
<p><strong>70</strong>件已付款</p>
</div>
<div class="buy">搶!</div>
</div>
</div>
</div>
</div>
*{
padding:0px;
margin:0px;
}
body{
font-family: '微軟雅黑';
}
.sl{
white-space: nowrap;
word-break: keep-all;
text-overflow: ellipsis;
}
#big{
width:950px;
height:416px;
margin:10px auto;
overflow: hidden;
}
#big>.box{
width:298px;
height:410px;
float: left;
position: relative;
overflow: hidden;
border:1px solid #ccc;
margin-left:19px;
}
#big>.box:first-child{
margin-left:0px;
}
#big>.box>.pic{
width:298px;
height:300px;
overflow: hidden;
}
#big>.box>.pic>img{
transition: all 500ms;
}
#big>.box:hover>.pic>img{
transform: scale(1.5);
}
#big>.box>.mask{
height:300px;
width:298px;
position: absolute;
left:-298px;
top:0px;
background:rgba(0,0,0,0.3);
transition: all 600ms;
color:#fff;
}
#big>.box>.mask>h2{
font-size: 18px;
margin:80px 0px 10px 10px;
}
#big>.box>.mask>p{
font-size: 12px;
margin:0px 0px 10px 10px;
}
#big>.box:hover>.mask{
left:0px;
}
#big>.box>.title>h2{
margin:10px auto;
width:288px;
height:20px;
line-height: 20px;
font-size: 14px;
color:#333;
overflow: hidden;
font-weight: normal;
}
#big>.box>.title>h2>span{
display: inline-block;
width:31px;
height:16px;
vertical-align: middle;
background: url('img/tu.png') no-repeat;
background-size:cover;
margin-right:5px;
}
#big>.box>.title>h3{
width:288px;
height:20px;
margin:0px auto;
font-size: 12px;
color:#666;
font-weight: 400;
}
#big>.box>.title>h3>i{
width:12px;
height:16px;
display: inline-block;
background:url('img/tu1.jpg') no-repeat;
vertical-align: middle;
}
#big>.box>.title>h3>span{
color:#f00;
margin:0 5px 0 5px;
}
#big>.box>.title>.price{
width:298px;
height:50px;
background:#e61414;
}
#big>.box>.title>.price>.zx_pr>span{
font-size: 20px;
}
#big>.box>.title>.price>.zx_pr{
width:83px;
height:50px;
line-height: 50px;
float: left;
margin-left:2px;
vertical-align: bottom;
font-size:38px;
color:#fff;
}
#big>.box>.title>.price>.buy{
width:56px;
height:50px;
line-height: 50px;
text-align: center;
background:url('img/tu3.png') no-repeat;
float:right;
color:#f00;
}
#big>.box>.title>.price>.xl_yp{
width:145px;
height:41px;
float: left;
margin:4px 0 0 8px;
font-size: 12px;
color:#fff;
}
#big>.box>.title>.price>.xl_yp>p>span{
margin-left:4px;
width:72px;
height:17px;
display: inline-block;
line-height: 17px;
text-align: center;
border-radius: 10px;
background:#ffb369;
}
#big>.box>.title>.price>.xl_yp>p:nth-child(2){
width:80px;
height:20px;
line-height: 20px;
text-align: center;
border-radius: 1px;
margin-top:5px;
background:rgba(0,0,0,0.2);
}
#big>.box>.title>.price>.xl_yp>p:nth-child(2)>strong{
margin-right: 5px;
font-size: 14px;
}
如圖
"點贊" "??評論" "收藏"
大家的支持就是我堅持創作下去的動力!?
?如果以上內容有任何錯誤或者不準確的地方,歡迎在下面 留個言指出、或者你有更好的想法,歡迎一起交流學習???????????
*請認真填寫需求信息,我們會在24小時內與您取得聯系。