python爬虫实例(百度图片、网站图片)
生活随笔
收集整理的這篇文章主要介紹了
python爬虫实例(百度图片、网站图片)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
爬蟲基本流程
1.百度圖片爬蟲
在這里有一個小技巧,百度圖片展示是下拉式的,要想看更多的圖片,需要滑動滾輪讓界面加載才可以查看。
普通的爬蟲對于百度圖片的url只會接受到未滾動滾輪前界面所展示的所有信息
因此這里有一個小技巧,如上圖紅框中的信息index,在這里用字符flip替換掉index,即可實現圖片分頁,但其實分頁圖片都是存在在一個界面的,也就意味著爬蟲時不需要對分頁做處理。
實現代碼如下
import re import requests import os # 1.拿到urlword=input('你想看有顏色的圖片嗎,請輸入:')if not os.path.exists(word):os.mkdir(word) url="https://image.baidu.com/search/flip?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word="+word head={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"} # 2.得到網頁源代碼r=requests.get(url,headers=head)#<response [200]> 200狀態碼 請求成功 #ret=r.text #ret 得到就是網頁源代碼 ret=r.content.decode('utf-8') #ret 得到就是網頁源代碼# 3.拿到所有圖片的url#"objURL" result=re.findall('"objURL":"(.*?)",',ret)# 4.保存所有圖片 for i in result:try:r = requests.get(i,timeout=3)except Exception as e:print(e)continue#取幾張圖片。取50張path = i[0:50]#判斷url后10位是否是圖片類型的結尾end=re.search(r'\.jpg$|\.jpeg$|\.gif$|\.png$',path)if end ==None:path = path + '.jpg'print(path)path= re.sub('/','',path)with open(word + '/' + path,'wb') as f:f.write(r.content)代碼中可以通過輸入自己想要的關鍵詞,修改想要的圖片數量參數,來下載對應的圖片
2.網站圖片
這種專門的圖片網站,通常包含分頁選項,以及每個圖片的鏈接,對應到圖片的詳細頁面,其中詳細界面通常包含1張以上的圖片。
因此爬蟲不僅需要對分頁做處理,同時需要對每一個頁的每一個鏈接下的詳細界面做處理獲取
實現代碼如下:
import os''' 頁面一共35 http://ailuotuku.com/page_1.html ''' from bs4 import BeautifulSoup#網頁解析 import re #正則匹配 import urllib.request,urllib.error #制定url import requests#創建正則表達式對象,表示規則 #圖片鏈接 findlink=re.compile(r'<a href="(.*?)" target="_blank">') #圖片標題 findtitle=re.compile(r'<h1>(.*?)</h1>') #圖片 findimg=re.compile(r'<img.*?src="(.*?)".*?>',re.S)#爬數據 def getdata():#1.調用獲取頁面的函數for i in range(1,36):url="http://ailuotuku.com/page_%s.html"%ihtml1=askURL(url)#2.解析數據soup1=BeautifulSoup(html1,"html.parser")for item1 in soup1.find_all('div',class_="update_area_content"):item1=str(item1)#re庫查找正則表達式link=re.findall(findlink,item1)for j in link:j=str(j)html2 = askURL(j)soup2 = BeautifulSoup(html2, "html.parser")data_title=[]data_img=[]for item2 in soup2.find_all('div', class_="main_left single_mian"):item2=str(item2)title=re.findall(findtitle,item2)for item3 in soup2.find_all('div',class_='content_left'):item3=str(item3)image=re.findall(findimg,item3)for img in image:data_img.append(img)print(title)print(data_img)#保存圖片for filename in title:for url in data_img:file=url.split('/')[-1]head = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.93 Safari/537.36"}response = requests.get(url, headers=head)if not os.path.exists('data/%s'%filename):os.mkdir('data/%s'%filename)with open('data/%s/'%filename + file, 'wb') as f:f.write(response.content)else:passdef askURL(url):head={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.93 Safari/537.36"}#偽裝瀏覽器request=urllib.request.Request(url,headers=head)html=""try:response=urllib.request.urlopen(request)html=response.read().decode("utf-8")except urllib.error.URLError as e:if hasattr(e,"code"):print(e.code)if hasattr(e,"reason"):print(e.reason)return htmldef main():data=getdata()if __name__ =="__main__":main()總結
以上是生活随笔為你收集整理的python爬虫实例(百度图片、网站图片)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬虫实例之一
- 下一篇: n个数里找出前m个数(或者 从10亿个浮