网址:https://www.doutula.com/photo/list/?page=1
这是一个写的很规范的网站,就是意味着很好爬。哈哈哈。首先分析网页元素,在浏览器中打开开发者工具检查元素。点击network,我使用的是火狐浏览器,所以点击网络就行,然后网页刷新。这里为了过滤掉其他没用的文件,选择图像。可以看到有很多的图像链接,我要的就是这些文件。如图:
然后随便选择一个文件点击进去,这里是可以预览的,可以看到它的各种信息,如图:
下面开始写代码:
首先导包:
import requests
import os
import re
这次是使用正则表达式来解析网页
因为我想爬取的不是仅仅一张网页上的图片,所以这里我是使用一个循环,也可以不使用,直接拿出来即可
url = 'https://www.doutula.com/photo/list/?page=1'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/63.0'
}
response = requests.get(url,headers = headers).text
print(response)
这里要注意的一点是火狐的User-Agent竟然无法使用!!!!!!!所以需要换成其他浏览器的。会报错的。。。
可以打印网页内容先看一下
然后就开始正则匹配图片链接
reg = r'data-original="(.*?)"'
images_urls = re.findall(reg,respose)
#print(images_urls)
def download(url1):
res = requests.get(url1,headers = header).content
return res
for images_url in images_urls:
image_name = images_url.split('/')[-1][:-4]
print(image_name)
image = download(images_url)
with open('./images/%s'%image_name,'wb')as file:
file.write(image)
print("the"+str(n)+'page has completed copying')
这里也是开头的for循环里的内容,使用切片来正确打印图片的名字,提前在当前目录建立images文件夹
完整代码很短,如下:
# !/usr/bin/env python
# -*- coding:utf-8 -*-
#author named sunxth
#IDE pycharm
import requests
import re
import os
def mainpy():
for n in range(1,30):
url = "https://www.doutula.com/photo/list/?page="+str(n)
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.204 Safari/537.36'}
respose = requests.get(url,headers = header).text
#print(respose)
reg = r'data-original="(.*?)"'
images_urls = re.findall(reg,respose)
#print(images_urls)
def download(url1):
res = requests.get(url1,headers = header).content
return res
for images_url in images_urls:
image_name = images_url.split('/')[-1][:-4]
print(image_name)
image = download(images_url)
with open('./images/%s'%image_name,'wb')as file:
file.write(image)
print("the"+str(n)+'page has completed copying')
if __name__ == '__main__':
mainpy()
使用效果如下: