python简单爬取斗图图片(自学第十天)
生活随笔
收集整理的這篇文章主要介紹了
python简单爬取斗图图片(自学第十天)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、前期準備
(一).我們要爬取的頁面
1,我們要爬取的網站為:https://www.doutula.com/photo/list/?page=1
2,獲取請求頭,來模擬瀏覽器瀏覽,不讓網站直接就暴露我們是python,怎么獲取請求頭呢,很簡單,按f12(右鍵檢查)
很好,你已經會了請求頭,那么現在就開始用工具把。
3,所以我們前期的代碼是這樣的:
def get_url(url): #我們的請求頭信息headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'} #定義一個main函數 def main():for x in range(1,10): #定義一個循環,設置我們要爬取的頁數url = 'https://www.doutula.com/photo/list/?page=%d'%xget_url(url) #函數調用if __name__ == '__main__':main()二、獲取網頁的信息
(一),用requests來獲取我們頁面信息,安裝如下
? pip install?requests??-i https://pypi.tuna.tsinghua.edu.cn/simple?
(二),用etree來使用我們xpath
代碼為:
def get_url(url): #我們的請求頭信息headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}response =requests.get(url,headers=headers)#打印我們的信息print(response)response =requests.get(url,headers=headers)test = response.texthtml = etree.HTML(test)#定義一個main函數 def main():for x in range(1,10): #定義一個循環,設置我們要爬取的頁數url = 'https://www.doutula.com/photo/list/?page=%d'%xget_url(url) #函數調用if __name__ == '__main__':main()(三),使用xpath來獲取我們的圖片和標題
這里是網站放置圖片和文本的地方,我們使用xpath獲取到了整頁中所以圖片的地址和標題
代碼如下:
img_url =html.xpath("//div[@class ='page-content text-center' ]//img[@class !='gif']")(四)全部代碼
import requests from lxml import etree import os import re from urllib import request i = 1 def get_url(url):global iheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}response =requests.get(url,headers=headers)test = response.texthtml = etree.HTML(test)img_url =html.xpath("//div[@class ='page-content text-center' ]//img[@class !='gif']")for img in img_url:img_url1 = img.get('data-original')img_name = img.get('alt')img_name = re.sub(r'!@#$%^&*()~`,?\/','',img_name)suffix = os.path.splitext(img_url1)[1]filenme = img_name+suffix# print(filenme)print("正在下載:{}".format(filenme))request.urlretrieve(img_url1,'aaa/'+filenme)print("=" * 30)print("正在下載%d頁" % i)i += 1 def main():a = input("請輸入你要爬取的頁數:")for x in range(1,a):url = 'https://www.doutula.com/photo/list/?page=%d'%xget_url(url)if __name__ == '__main__':main()?
總結
以上是生活随笔為你收集整理的python简单爬取斗图图片(自学第十天)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑莓应用下载网站
- 下一篇: IAR设置flash偏移地址问题icf文