Pycharm爬虫实战之爬取网站图片python源码大全自定义搜索整理精简版DIY

本文分享了使用PyCharm进行爬虫实战的三个案例,包括爬取Pexels网站图片、百度搜索引擎数据以及中关村壁纸。每个案例都提供了详细的操作步骤和源码,并展示了运行效果。
摘要由CSDN通过智能技术生成

源码系列1:

大概的思路和上一篇差不多,不同的是不同的网站有不同的反爬策略

爬取的网站是:https://www.pexels.com/

参考:https://blog.csdn.net/qq_32511479/article/details/76050973

源码如下:

import requests
import re
import os
import time

def get_url(url):
    kw = {
   'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)'}
    try:
        r = requests.get(url, headers=kw)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r
    except:
        print('error!')

def get_photourl(photo_url):
    kw = {
   'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)'}
    try:
        r = requests.get(photo_url, headers=kw)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r
    except:
        return 'error'

def get_photos(url, new_fpath):
    result = get_url(url)
    pattern = re.compile(r'src="https://images.pexels.com/photos/(\d+)/(.*?)\?h=350&auto=compress&cs=tinysrgb"', re.S)
    
    items = re.findall(pattern, result.text)

    for item in items:
        try:
            photo_url = 'https://static.pexels.com/photos/' + str(item[0]) + '/' + str(item[1])
            # 把图片链接中的images,改成了static
            save(photo_url, item, new_fpath)
            time.sleep(1)
        except:
            continue

def makedir(new_fpath, i, key):
    E = os.path.exists(new_fpath)
    if not E:
        os.makedirs(new_fpath)
        os.chdir(new_fpath)
        print('文件夹' + key + '_page' + str(i + 1) + '创建成功!')
    else:
        print('文件夹已存在!')

def save(photo_url, item, new_fpath):
    Final_fpath = new_fpath + '/' + str(item[0]) + str(item[1])

    print('正在下载图片......')

    result = get_photourl(photo_url)
    if result != 'error':
        print('下载成功!'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海宝7号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值