爬取网址
- https://findicons.com/pack/2787/beautiful_flat_icons
- import requests
- import re
- import time
- def get_html(url):
- headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) ApplewebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.18 Safari/537.36"} #访问的请求头, 模拟浏览器的请求头
- request=requests.get(url,headers=headers) #给一个 get 请求, 把请求结果保留下来
- html=request.text #把结果用代码的方式呈现
- return html
- def get_image(html):
- reexpr=re.compile('<img src="https://findicons.com/files/(.*?)"',re.S) #re 表达式, re.S 表示可以换行
- a=re.findall(reexpr,html) #从网页源码中找到所有符合正则的条件
- global count
- for i in a :
- full_web="https://findicons.com/files/"+i #因为正则表达式匹配时总会有两三张不同的图, 所以上面的正则只是匹配到 id 后面的内容, 这里把整个 url 给拼接起来了
- full_web_image=requests.get(full_web) #使用获取的网址再去发送请求, 获取图片
- with open(r"F:\image\%d 图. jpg"%count,"wb") as f: #保存图片
- print("正在抓取第 %d 张图片"%count)
- f.write(full_web_image.content)
- time.sleep(1)
- count+=1
- # return count
- count=1 #定义一个全局的计数器
- def main(offest=1):
- url = "https://findicons.com/pack/2787/beautiful_flat_icons/"+str(offest)
- html_text = get_html(url)
- get_image(html_text)
- if __name__ == "__main__":
- offest=input("请输入想爬取到第几页, 默认爬取第一页")
- if offest=="":
- main()
- else:
- for i in range (1,int(offest)+1):
- main(i)
来源: http://www.bubuko.com/infodetail-2649635.html