分享一次用Python抓取网络图片的经历

最近学完了Python语言基础语法,然后计划小试牛刀,抓取网络图片
以下是这次的代码。
首先先说下,这个代码还是很粗糙,如果对方东西太多自己电脑太弱鸡肯定会内存泄漏导致崩溃,解决办法就是将每一个抓取网络连接的方法写成生成器函数,这样就不那么耗内存,但是由于今天实在太晚了加上现在还在被代理的东西反着确实没心情优化。。。顺带,弱弱的问一句,设置代理只能自己买服务器吗?

import requests,os
from bs4 import BeautifulSoup
url='http://588ku.com/?h=bd&sem=1'
localdir='E:/book_test/imgs2'
time_out=100
def get_response(url):
    '''获得网络回应'''
    global links
    req = requests.get(url,timeout=time_out)

    req.close()
    return req.text

def get_tags(text,ta):
    '''找到你要的标签'''
    soup = BeautifulSoup(text, 'lxml')
    tags = soup.select(ta)
    return tags

def find_href(tags,bz):
    '''从标签中获取指定元素'''
    links = []
    for tag in tags:
        link = str(tag[bz])
        if link.startswith('http'):
            links.append(link)
    return list_helper(links)

def list_helper(myli):
    return list(set(myli))
# def printhelp(lists):
#     for l in lists:
#         print(l)
def find_img_links(tex):
    img_tag = get_tags(tex, 'img')
    img_links = []
    for img in img_tag:
        try:
            if img['data-original']:
                img_link = img['data-original']
                if str(img_link).startswith('http'):
                    img_links.append(img_link)
            if img['src']:
                img_link=img['src']
                if str(img_link).startswith('http'):
                    img_links.append(img_link)
        except KeyError:
            print('img link error!',img_link)
    return  list_helper(img_links)

def get_name(lll):
    lists =str(lll).split('/')
    for i in lists:
        if i is None:break
        if str(i).endswith('.jpg!'): return i[:-1]
        if str(i).endswith('.jpg'):return i
        if str(i).endswith('png'):return i


res=get_response(url)
mytag=get_tags(res,'a[href]')
mylinks=find_href(mytag,'href')#得到首页的所有链接


def circle(mylinks):
    for url in mylinks:
        text = get_response(url)
        new_tag_a = get_tags(text, 'a[href]')
        imglinks = find_img_links(text)
        for imglink in imglinks:
            download(imglink)
        new_a_link = find_href(new_tag_a, 'href')  # 得到所有连接点进去的返回结果链接
        # if new_a_link:circle(new_a_link)#这个东西是用来找打开的链接里面的另外的网页的,但是这么干的话,不知道那么多图片我电脑会不会GG所以注释掉啦。试了下运行是没问题的,不过我不愿意等那么久

def download(imglink):
    content = requests.get(imglink,timeout=time_out)
    name = get_name(imglink)
    try:
        if not os.path.exists(localdir): os.mkdir(localdir)
        os.chdir(localdir)
        if os.path.exists(name):return
        open(name, 'wb').write(content.content)
    except TypeError:print('download error')
    finally:content.close()


# [tests.append(get_response(url))for url in mylinks]

circle(mylinks)

然后代理那个玩意儿,还要慢慢研究。。。
对了,碰到的问题就是。。。懒得贴了,反正运行一次就知道,远程主机强行关闭了一个现有连接。。。然后,下载过程中还会出一些错误,在两个try里面,已经打印出来了。过两天再研究吧。想起来了来更新
requests真好用,bs4页好用。不过如果不想用第三方库的话可以考虑xml.parsers或者xml.dom 不想用request的话也可以考虑用urllibe

接下来的目标是做一个能方便下载指定图片的工具,然后把这两个功能结合起来,打包。嗯,初步设想是点击想要的图片就可以下载。不过要如何从浏览器图片获得地址暂时未知,下载倒是简单,只要能轻松获得地址其他都不是问题了。

你可能感兴趣的:(Python学习,Python练习小项目)