Python——网络爬虫(爬取网页图片)

版权声明:编写不易,转载请注明出处,谢谢。 https://blog.csdn.net/qingshui23/article/details/78797069

最近在学习 Python, 然后就试着写了一个简单的Python小程序,爬取一个网页的图片,不得不说 Python 真的强大,以下是爬取 NEFU Online Judge 网站的代码。

吐槽:其实爬取所想要东西的时候,正则表达式真的很重要,这个需要好好学习一下。
代码:

'''
批量下载 NEFU Online Judge 的图片

爬取NEFU Online Judge网站首页的图片,保存到指定路径文件夹下
'''
import urllib.request,socket,os,re,sys

targetPath  = "D:\\MyPython\\爬虫\\03_images"
def saveFile(path):
    #检测当前路径是否存在
    if not os.path.isdir(targetPath):
        os.mkdir(targetPath)
    # 设置每个图片的路径
    pos = path.rindex('/') #rindex()  返回子字符串 str 在字符串中最后出现的位置
    ans = os.path.join(targetPath,path[pos+1:])
    return ans

url = "http://acm.nefu.edu.cn/"

#请求

req = urllib.request.Request(url)
#爬取的结果

res = urllib.request.urlopen(req)

#将结果显示
data = str(res.read())

tmp = "http://acm.nefu.edu.cn//JudgeOnline/"
pattern = r'([\w./]+\.(jpg|JPG|png|PNG|gif))'
#pattern = r'(https:[^s]*?(jpg|JPG|png|PNG|gif))'
imgurl = re.findall(pattern, data)#re.findall 正则表达式

for link,value in imgurl:
    url = tmp+str(link)
    print(url) #打印链接
    try:
        urllib.request.urlretrieve(url,saveFile(url))#urlretrieve() 方法直接将远程数据下载到本地
    except:
        print("爬取失败")

猜你喜欢

转载自blog.csdn.net/qingshui23/article/details/78797069