爬取你所想的图片

本文介绍了如何使用Python通过正则表达式从网页源代码中提取图片数据。提供了两个案例,包括一个简单的预览案例和一个更深入的爬取任何相关图片的实战案例。
摘要由CSDN通过智能技术生成

数据在网页源代码中用正则

案例一(饭前点心)

import urllib.request
url = 'https://tieba.baidu.com/p/5734214281'
response=urllib.request.urlopen(url)
html=response.read()
html=html.decode('utf-8')
html

运行截图如下:
在这里插入图片描述

import re
reg=r'src="(.+?\.jpg)" pic_ext'  #r在这里是来识别双引号的,避免与python中字符串的双引号用法冲突
imgre=re.compile(reg)#编译正则表达式
imglist=re.findall(imgre,html)
x=1
for i in imglist:
    print(x)   
    urllib.request.urlretrieve(i,'C:\\Users\\18487\\Desktop\\picture\\%s.jpg'%x) 
    x+=1
print("done")

案例二:爬取任何你想要的有关图片(大餐来啦)

import requests
import re 
import os
import time

x = 1 #图片计数




def getHtml(url):
    #proxies={"http":"http://1.197.16.148:9999"} #代理IP,反反爬
    #headers={'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
    #'Cookie': '_tact=MWJkMmI3MzEtOTYx' } #iPhone的header并带有cookie
    #html=requests.get(url,headers=headers,proxies=proxies).text 
    headers={
   'Accept-Encoding':'gzip,deflate',
    'Accept-Language':'zh-CN',
    'Cache-Control':'no-cache',
    'Connection':'keep-alive',
    'Pragma':'no-cache',
    'User-Agent':'Mozilla/5.0 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值