概要
在网络时代,图片是信息传递的重要形式之一,而Python作为一种多用途的编程语言,可以用来编写爬虫从网页上获取图片,并保存到本地。本文将介绍如何使用Python爬虫实现这一功能,并探讨一些进阶技巧。
实现
(1)请求对象定制
python
# 请求对象定制
def create_request(page):
if 1 == page:
url = 'https://sc.chinaz.com/tupian/huacaotupian.html'
else:
url = 'https://sc.chinaz.com/tupian/huacaotupian_' + str(page) + '.html'
# 防止UA(User-Agent)检查
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
}
request = urllib.request.Request(url=url, headers=headers)
return request
(2)获取网页源码
python
# 获取网络源码
def get_content(request):
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
return content
(3)解析并下载图片
python
# 下载
def down_load(content):
tree = etree.HTML(content)
name_list = tree.xpath('//div[@class="container"]//div/div/img/@alt')
img_list = tree.xpath('//div[@class="container"]//div/div/img/@data-original')
# for i in range(len(name_list)):
# print('name', i)
# for i in range(len(img_list)):
# print('src', i)
for i in range(len(name_list)):
urllib.request.urlretrieve(url= 'https:' + img_list[i], filename='./out_Data/img/' + name_list[i] + '.png')
解析网页源码这里用到了xpath,xpath是lxml下的一个包,使用时,需要导入:
python
from lxml import etree
完整代码
完整代码如下:
python
import urllib.request
from lxml import etree
# 分析页码之间的关系
# get请求
# https://sc.chinaz.com/tupian/huacaotupian.html 1
# https://sc.chinaz.com/tupian/huacaotupian_2.html 2
# https://sc.chinaz.com/tupian/huacaotupian_3.html 3
# https://sc.chinaz.com/tupian/huacaotupian_4.html 4
# 请求对象定制
def create_request(page):
if 1 == page:
url = 'https://sc.chinaz.com/tupian/huacaotupian.html'
else:
url = 'https://sc.chinaz.com/tupian/huacaotupian_' + str(page) + '.html'
# 防止UA(User-Agent)检查
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
}
request = urllib.request.Request(url=url, headers=headers)
return request
# 获取网络源码
def get_content(request):
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
return content
# 下载
def down_load(content):
tree = etree.HTML(content)
name_list = tree.xpath('//div[@class="container"]//div/div/img/@alt')
img_list = tree.xpath('//div[@class="container"]//div/div/img/@data-original')
# for i in range(len(name_list)):
# print('name', i)
# for i in range(len(img_list)):
# print('src', i)
for i in range(len(name_list)):
urllib.request.urlretrieve(url= 'https:' + img_list[i], filename='./out_Data/img/' + name_list[i] + '.png')
if __name__ == '__main__':
start_page = int(input('请输入起始页码: '))
end_page = int(input('请输入截止页码: '))
for page in range(start_page, end_page + 1):
print('下载至第' + page + '页')
# 请求对象定制
request = create_request(page)
# 获取网页源码
content = get_content(request)
# 下载数据
down_load(content)