python图片爬虫入门笔记

167 阅读1分钟

背景:CTF入门,发现连python脚本都不会写,遂花一个晚上学了python爬图片。(GHSSDYSCL???)

目标:photos of Scarlett Johansson on doubxx.com

1.分析:

观察页面,一页显示30张,一共120页 image.png

观察url,以start后面的数字作为该页面第一张图片的序号

2.python3代码(url做了处理)

import requests
import re
from bs4 import BeautifulSoup
url='https://movie.xxxxx.com/celebrity/1054453/photos/'
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}#伪造头文件
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')#创建soup对象,html.parser是解析器种类,目前看不懂
images=soup.find_all('img',{'class':''})#images是一个list,img是标签,class结合实际为空

'''
一页显示30张,例如:
https://movie.xxxx.com/celebrity/1054453/photos/?start=30
一共有119页
'''
#j=1,2,...,119
#k=0,1,2,...,118
#结合实际情况,爬前30j张
for k in range(118):
    j=k+1
    if j>1:#更新界面
        url='https://movie.xxxxxx.com/celebrity/1054453/photos/?start='+str(30*k)
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        images=soup.find_all('img',{'class':''})
    for i in range(30):
        image=images[i]
        src=image['src']#取得image的src
        no=-29+30*j+i#算了下序号,写的有点麻烦
        target=requests.get(src,timeout=5).content#target就是图片,如果请求时间超过5s就算了吧下一位
        f = open(str(no) + '.jpg', 'wb')#创建文件对象f,wb表示以二进制打开
        f.write(target)#写入图片
        print(str(no))#在终端可以看到爬到第几张了
        f.close()#关掉f

3.写在后面:

① 这是最最简单的爬虫。查阅资料过程中发现还有好多东西不会啊qwq。本来想用正则,发现我顶不住。先把正则学扎实了再说吧

② 其实爬到的图片是缩略图,原图要解析url进入页面,然后再查看原图。逻辑很清晰,原理没问题,但是现在很饿,就懒得搞了。