爬取图片与爬取文本内容相似,只是需要加上图片的url,并且在查找图片位置的时候需要带上图片的属性。
这里选取了一个4K高清的壁纸网站(彼岸壁纸https://pic.netbian.com)进行爬取。
具体步骤如下:

# url url = "https://pic.netbian.com/4kmeinv/" # UA伪装 用下载好的库中别人写好的UA head = {"User-Agent": fake_useragent.UserAgent().random} # 发送请求 response = requests.get(url, headers=head) # 获取想要的数据 res_text = response.text 
# 数据解析 获取所有的li标签,并存放在li_list中 tree = etree.HTML(res_text) li_list = tree.xpath("//div[@class='slist']/ul/li") for li in li_list: # 图片的url img_url = "https://pic.netbian.com" + "".join(li.xpath("./a/img/@src")) # 发送请求 img_response = requests.get(img_url, headers=head) # 获取想要的数据 img_content = img_response.content # pic_name = 0 这次的代码封装在函数中,将这个变量放在了函数外面,给获取的图片编号 # 将pic_name定义为全局变量,方便调用 global pic_name with open(f"./picLibbb/{pic_name}.jpg", "wb") as fp: fp.write(img_content) pic_name += 1 第一页的网址
第二页的网址

第三页的网址

url = "https://pic.netbian.com/4kmeinv/" request_pic(url) for i in range(1,10): next_url = f"https://pic.netbian.com/4kmeinv/index_{i}.html" request_pic(next_url) 完整代码:
# 获取图片数据 import os.path import fake_useragent import requests from lxml import etree # UA伪装 head = {"User-Agent": fake_useragent.UserAgent().random} pic_name = 0 def request_pic(url): # 发送请求 response = requests.get(url, headers=head) # 获取想要的数据 res_text = response.text # 数据解析 tree = etree.HTML(res_text) li_list = tree.xpath("//div[@class='slist']/ul/li") for li in li_list: # 图片的url img_url = "https://pic.netbian.com" + "".join(li.xpath("./a/img/@src")) # 发送请求 img_response = requests.get(img_url, headers=head) # 获取想要的数据 img_content = img_response.content global pic_name with open(f"./picLib/{pic_name}.jpg", "wb") as fp: fp.write(img_content) pic_name += 1 if __name__ == '__main__': # 创建存放照片的文件夹 if not os.path.exists("./picLib"): os.mkdir("./picLibbb") # 网站的url url = "https://pic.netbian.com/4kdongman/" request_pic(url) for i in range(1,10): next_url = f"https://pic.netbian.com/4kmeinv/index_{i}.html" request_pic(next_url) 爬取后的效果如下:
上一篇:客运大亨哪里下载破解版
下一篇:酷派改变者s1的系统