Python爬虫爬取图片
需要用到的库:
os
time
request
lxml
代码源码如下:
import os
import time
import requests
from lxml import etree
#建议headers写全 也可以只写user-agent和cookie
headers = {
'User-Agent':'xxxxxx',
'Accept': 'xxxxxx',
'Accept-Encoding': 'xxxxxx',
'Accept-Language': 'xxxxxx',
'Connection': 'xxxxxx',
'Cookie': 'xxxxxx',
'Referer': 'xxxxxx'
}
#单页面爬取
#先请求获得想要爬取图片的当前网页源码
#可以使用print打印到控制台分析也可以在网页中使用F12查看分析
response = requests.get('http://xxxxxx.com/xxx?xxx',headers=headers)
# print(response.content.decode())
html = etree.HTML(response.content.decode())
#使用xpath获取图片源
#img标签下的
imgs = html.xpath("//img//@file")
for i in imgs:
#睡眠3秒
time.sleep(3)
#可能需要进行链接拼接
url2 = ("http://xxxxxx.com/"+i)
print(url2)
#保存图片名
#以'/'做分隔符 截取倒数第一个作为图片名
file_name = url2.split('/')[-1]
print(file_name)
#请求图片源
#content中间存的是字节码 保存图片使用content
img_data = requests.get(url2, headers=headers).content
#创建文件夹
if not os.path.exists('./xx'):
os.mkdir('./xx')
img_path = './xx/' + file_name
with open(img_path, 'wb') as f:
f.write(img_data)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
xpath 选择