import requests
import re#根據url獲取網頁html內容
def getHtmlContent(url):page = requests.get(url)return page.texthtml = getHtmlContent('https://tieba.baidu.com/p/4840106397')#以html中使用re模塊解析出所有jpg圖片的url
#百度貼吧html中jpg圖片的url格式:<img...src="xxx.jpg" width=....>
def getJPGs(html):#解析jpg圖片url的正則jpgReg = re.compile(r'<img.*?src="(.*?\.jpg)"')#解析出jpg的url列表jpgs = re.findall(jpgReg,html)return jpgsjpgs = getJPGs(html)
print(jpgs)html = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E5%9B%BE%E7%89%87&fr=search'#用圖片url下載圖片并保存成制定文件名
def downloadJPG(imgUrl,fileName):#可自動關閉請求和相應的模塊from contextlib import closingwith closing(requests.get(imgUrl,stream=True)) as resp:with open(fileName,'wb') as f:for chunk in resp.iter_content(128):f.write(chunk)#批量下載圖片,默認保存在當前目錄下
def batchDownloadJPGs(imgUrls,path='./'):#用于給圖片命名count =1for url in imgUrls:downloadJPG(url,''.join([path,'{0}.jpg'.format(count)]))print('下載完成第{0}張圖片'.format(count))count =count+1#封裝,從百度貼吧網頁下載圖片
def download(url):html = getHtmlContent(url)jpgs = getJPGs(html)batchDownloadJPGs(jpgs)def main():url = 'http://tieba.baidu.com'download(url)if __name__ =='__main__' :main()
進入爬蟲學習:
首先導包
import requests
import re
?獲取網頁源碼,確定可以獲取,獲得了之后可以操作的整體對象
#根據url獲取網頁html內容
def getHtmlContent(url):page = requests.get(url)return page.texthtml = getHtmlContent('https://tieba.baidu.com/p/4840106397')
?獲取圖片,用到的就是很神奇的正則表達式,本人起初覺得很一般,沒什么不得了,但是用的時候,卻發現大道至簡。
#以html中使用re模塊解析出所有jpg圖片的url
#百度貼吧html中jpg圖片的url格式:<img...src="xxx.jpg" width=....>
def getJPGs(html):#解析jpg圖片url的正則jpgReg = re.compile(r'<img.*?src="(.*?\.jpg)"')#解析出jpg的url列表jpgs = re.findall(jpgReg,html)return jpgsjpgs = getJPGs(html)
print(jpgs)html = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E5%9B%BE%E7%89%87&fr=search'
?接下來就是獲取圖片,照著跑就行。
#用圖片url下載圖片并保存成制定文件名
def downloadJPG(imgUrl,fileName):#可自動關閉請求和相應的模塊from contextlib import closingwith closing(requests.get(imgUrl,stream=True)) as resp:with open(fileName,'wb') as f:for chunk in resp.iter_content(128):f.write(chunk)#批量下載圖片,默認保存在當前目錄下
def batchDownloadJPGs(imgUrls,path='./'):#用于給圖片命名count =1for url in imgUrls:downloadJPG(url,''.join([path,'{0}.jpg'.format(count)]))print('下載完成第{0}張圖片'.format(count))count =count+1#封裝,從百度貼吧網頁下載圖片
def download(url):html = getHtmlContent(url)jpgs = getJPGs(html)batchDownloadJPGs(jpgs)def main():url = 'http://tieba.baidu.com'download(url)if __name__ =='__main__' :main()
?