爬取美桌壁纸之可爱小狗狗
最近在学爬虫,用课堂案例来巩固下学习内容,爬取的是美桌壁纸。
爬取第一页每个跳转链接的第一个图片
以下是首页面
跳转的页面:
import requests
from lxml import etree # 用lxml库对网页进行解析
import os
url = 'http://www.win4000.com/zt/gou.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
}
response1 = requests.get(url, headers=headers)
response1_x = etree.HTML(response1.content) # 解析response
dog1 = response1_x.xpath('//div[@class="tab_box"]//li/a/@href')[:-5] # 获取所有封面小狗图像的跳转链接;最后五个匹配到的不是链接,排除掉
# 尝试过 //div[@class="tab_box"][1]//li/a/img/@src 这样直接获取封面图片,但是得到的链接不是图片链接,因此只能进入跳转页面获取
n = 0
for d in dog1:
n += 1 # 用作图片序号命名,否则每次循环图片会被覆盖
response2 = requests.get(d, headers=headers) # 获取每个小狗图像的跳转链接
response2_x = etree.HTML(response2.content) # 解析链接
dog2 = response2_x.xpath('//div[@class="pic-meinv"]/a/img/@src')[0] # 寻找该跳转链接中的小狗图像url
response3 = requests.get(dog2, headers=headers) # 获取该url的图像内容
if not os.path.exists('./img'): # 判断文件夹是否存在,不存在则创建
os.mkdir('./img')
img_name = './img/'+str(n)+'.jpg' # 建立单个jpg文件用以写入url内容,注意str的转换
file = open(img_name, 'wb') # 以二进制的形式打开jpg文件
file.write(response3.content) # 写入url内容
file.close()
图片:
爬取第一页跳转链接的所有图片
首先观察每张图片的链接有什么不同。
1:http://www.win4000.com/wallpaper_detail_167046.html
2:http://www.win4000.com/wallpaper_detail_167046_2.html
3:http://www.win4000.com/wallpaper_detail_167046_3.html
可以发现第一张图片的链接其实省略了一个‘_1’,接下来只要获取该系列图片的个数,然后遍历就ok了。
import requests
from lxml import etree # 用lxml库对网页进行解析
import os
url = 'http://www.win4000.com/zt/gou.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
}
response1 = requests.get(url, headers=heade