Python爬虫练习:爬取素材网站数据

时间:2022-07-26
本文章向大家介绍Python爬虫练习:爬取素材网站数据,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

在工作中的电子文案、ppt,生活中的新闻、广告,都离不开大量的素材,而素材网站随之应运而生

先看下效果图

而今天的爬取目标是素材网站

http://www.sccnn.com/

基本环境配置

  • python 3.6
  • pycharm
  • requests
  • parsel

爬虫代码

请求网页

import requests
import reurl = 'http://www.sccnn.com/shiliangtuku/default({}).html'.format(page)
headers = {    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
}response = requests.get(url=url, headers=headers)
response.encoding = response.apparent_encoding

分析网页,解析数据

import parsel
r = re.findall('<a href="(.*?)" target="_blank">', response.text)
for i in urls:
    page_url = 'http://www.sccnn.com' + i
    response_2 = requests.get(url=page_url, headers=headers)
    response_2.encoding = response_2.apparent_encoding    selector = parsel.Selector(response_2.text)    title = selector.css('#LeftBox h2::text').get()
    img_url = selector.css('#LeftBox .PhotoDiv img::attr(src)').get()

保存数据

def downlaod(title, url):
    path = 'D:\python\demo\素材网站\img\' + title + '.jpg'
    response = requests.get(url=url, headers=headers)
    with open(path, mode='wb') as f:
        f.write(response.content)
        print('正在下载{}'.format(title))

运行效果: