本片讲解如何爬取静态网页中的图片
老样子,导入requests库和xpath库
import requestsfrom lxml import etree
爬取目标地址为:https://sc.chinaz.com/tupian/fengjing.html
思路:请求网页地址,通过xpath解析出图片地址,再次请求图片地址,获取二进制数据并保存
代码:
#导库import requestsfrom lxml import etree#网页地址url = 'https://sc.chinaz.com/tupian/fengjing.html'#通过requests请求html = requests.get(url).content.decode('utf-8')#xpath解析html = etree.HTML(html)#提取图片地址imgs = html.xpath('//*[@id="container"]/div/div/a/img/@src2')#合并为标准网址imgs = ['http:'+x for x in imgs]#再次请求图片地址并保存for i in imgs: data = requests.get(i).content with open(f"img/{i.split('/')[-1]}",'wb') as f:#需要在当前目录手动新建一个名为img的文件夹 f.write(data)
当前页面就保存完了,通过点击第二页网址的变化可以得出,我们可以通过请求不同的网址来实现翻页,可以将代码修改为
import requestsfrom lxml import etree#增加一个for循环来实现1到10页的翻页效果,由于第一页与其他页地址不同,所以增加一个判断import requestsfrom lxml import etreefor n in range(1,11): if n == 1 : url = 'https://sc.chinaz.com/tupian/fengjing.html' else: url = f'https://sc.chinaz.com/tupian/fengjing_{n}.html' #通过requests请求 html = requests.get(url).content.decode('utf-8')#xpath解析 html = etree.HTML(html)#提取图片地址 imgs = html.xpath('//*[@id="container"]/div/div/a/img/@src2')#合并为标准网址 imgs = ['http:'+x for x in imgs]#再次请求图片地址并保存 for i in imgs: data = requests.get(i).content with open(f"img/{i.split('/')[-1]}",'wb') as f:#需要在当前目录新建一个名为img的文件夹 f.write(data)