Python爬虫-爬取科比职业生涯高清图集
生活随笔
收集整理的這篇文章主要介紹了
Python爬虫-爬取科比职业生涯高清图集
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前面學習了Python爬取豆瓣電影Top250的數據,爬取的信息是電影信息的文本信息,但是在互聯網上流行的圖片才有更大的吸引力,本篇我們來使用python爬取網頁上的圖片并保存在本地硬盤上,很興奮吧,Let's Go!
使用Python版本:3.7
第三方庫
requests: 解析url (強大,你不得不用!)
beautifulsoup4:不會正則表達式童鞋的福音,可以容易的提取到html文件中各種標簽及其屬性
安裝方法:?
pip install requests?
pip install beautifulsoup4
?
爬取目標網頁:科比職業生涯高清圖集 (來自百度網友分享)
https://baijiahao.baidu.com/s?id=1566820986637813&wfr=spider&for=pc
?
?分析網頁源代碼:發現需要的內容都集中在class="article-content"的div標簽中,而且需要的圖片都集中在class="large"的img標簽中
?
啥也不說了,直接上Python代碼吧!
KobeForever.py| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | ? | #?coding?=?utf-8 #?導入庫 import?os import?requests from?bs4?import?BeautifulSoup #?要爬取的科比職業生涯高清圖集URL url?=?'https://baijiahao.baidu.com/s?id=1566820986637813&wfr=spider&for=pc' #?設置headers,網站會根據這個判斷你的瀏覽器及操作系統,很多網站沒有此信息可能將拒絕你訪問 header?=?{ ????????'User-Agent':?'Mozilla/5.0?(Windows?NT?10.0;?WOW64)?AppleWebKit/537.36?(KHTML,?like?Gecko)?Chrome/50.0.2661.102?UBrowser/6.1.2107.204?Safari/537.36'} #?用get方法打開url并發送headers html?=?requests.get(url,?headers?=?header) #?使用自帶的html.parser解析,速度慢但通用 soup?=?BeautifulSoup(html.text,?'html.parser') #?打印結果?.text是打印出文本信息即源碼 #?print(html.text) #?所有的圖片內容都包含在class=article-content的大div中 all_div?=?soup.find('div',?class_?=?'article-content').find_all('div',?class_?=?'img-container') #?但是,實際上我們僅僅需要class=large的img標簽集合即可 all_img?=?soup.find_all('img',?class_?=?'large') for?img?in?all_img: ????src?=?img['src'] ????img_url?=?src ????#?打印出圖片的地址 ????print(img_url) ????#?實際上,我們更希望保存在我們的電腦硬盤上 ????root?=?'C:/KobeForever/' ????path?=?root?+?img_url.split('/')[-1] ????try:??#?創建或判斷路徑圖片是否存在并下載 ????????if?not?os.path.exists(root): ????????????os.mkdir(root) ????????if?not?os.path.exists(path): ????????????r?=?requests.get(img_url) ????????????with?open(path,?'wb')?as?f: ????????????????f.write(r.content) ????????????????f.close() ????????????????print("文件保存成功") ????????else: ????????????print("文件已存在") ????except: ????????print("爬取失敗") |
運行起來吧,GO!
最后再來一張霸氣的!
?
轉載于:https://www.cnblogs.com/MakeView660/p/9645068.html
總結
以上是生活随笔為你收集整理的Python爬虫-爬取科比职业生涯高清图集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 数据库类
- 下一篇: Python爬虫自学之第(③)篇——实战