aspx网页背景图片设置代码_python requests,BeautifulSoup批量下载360图片
生活随笔
收集整理的這篇文章主要介紹了
aspx网页背景图片设置代码_python requests,BeautifulSoup批量下载360图片
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
本代碼演示通過python的requests,BeautifulSoup庫批量下載360圖片,并保存在本機(jī)的路徑
代碼如下:
#BeautifulSoup庫是網(wǎng)頁爬蟲解析庫,主要用來對(duì)HTML源代碼進(jìn)行解析,方便顯示并讀取相應(yīng)的標(biāo)簽數(shù)據(jù)#1、首先導(dǎo)入相應(yīng)的庫import requestsfrom bs4 import BeautifulSoupimport randomimport osimport time#2、對(duì)網(wǎng)站進(jìn)行g(shù)et請(qǐng)求def gethtml(kward): try: url="https://image.so.com" #設(shè)置360網(wǎng)站的搜索頁面的前面部分網(wǎng)址 kw={"q":kward} #設(shè)置關(guān)鍵字變量kw headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"} # 設(shè)置網(wǎng)頁請(qǐng)求頭 response = requests.get(url, params=kw,headers=headers) ##偽裝瀏覽器對(duì)url進(jìn)行g(shù)et請(qǐng)求,傳遞的參數(shù)是kw response.encoding=response.apparent_encoding #根據(jù)網(wǎng)頁內(nèi)容解析出編碼格式并賦值給response.encoding html=response.text #將網(wǎng)頁源代碼賦值給html soup=BeautifulSoup(html,'html.parser') #使用html.parser對(duì)html代碼進(jìn)行解析,并賦值給soup變量 print(soup.head) #打印網(wǎng)頁源代碼的頭部信息 images=soup.find_all('img') #查找源代碼里所有的圖片標(biāo)簽 path="F://明星照片//"+kward+"//" #設(shè)置圖片的存儲(chǔ)本機(jī)的路徑 for img in images: #遍歷所有的img標(biāo)簽信息 print(img.attrs["src"]) #打印遍歷出來的圖片表情的src屬性值 url1=img.attrs["src"] #設(shè)置url1為遍歷出來的圖片表情的src屬性值 response1=requests.get(url=url1,headers=headers) #上行代碼偽裝瀏覽器對(duì)url1,即圖片網(wǎng)站進(jìn)行g(shù)et請(qǐng)求并將請(qǐng)求結(jié)果賦值給response1 response1.encoding=response1.apparent_encoding #根據(jù)網(wǎng)頁內(nèi)容解析出編碼格式并賦值給response1.encoding html1=response1.content #將圖片網(wǎng)址的二進(jìn)制源代碼賦值給html1 abspath=path+str(random.random())+".jpg" #設(shè)置存儲(chǔ)路勁為abspath with open(abspath,"wb") as f: #打開文件的絕對(duì)路徑,并對(duì)文件進(jìn)行寫入操作,并設(shè)置為f f.write(html1) #將源代碼寫入f文件 f.close() #關(guān)閉f文件 print(img.attrs["src"]+"下載成功") #打印下載成功的提示 time.sleep(0.2) #設(shè)置時(shí)間休眠0.2秒 except: #如果接受錯(cuò)誤時(shí) print("爬取失敗") #打印爬取失敗代碼運(yùn)行結(jié)果如下圖所示:
總結(jié)
以上是生活随笔為你收集整理的aspx网页背景图片设置代码_python requests,BeautifulSoup批量下载360图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聚类结果不好怎么办_使用bert-ser
- 下一篇: osgi框架和spring区别_最全15