日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

贴吧爬虫

發(fā)布時間:2023/12/19 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 贴吧爬虫 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import requests import re#根據(jù)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

?獲取網頁源碼,確定可以獲取,獲得了之后可以操作的整體對象

#根據(jù)url獲取網頁html內容 def getHtmlContent(url):page = requests.get(url)return page.texthtml = getHtmlContent('https://tieba.baidu.com/p/4840106397')

?獲取圖片,用到的就是很神奇的正則表達式,本人起初覺得很一般,沒什么不得了,但是用的時候,卻發(fā)現(xiàn)大道至簡。

#以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()

?

總結

以上是生活随笔為你收集整理的贴吧爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。