python爬虫访问页面并显示图片

来源:互联网 发布:淘宝如何优化关键词 编辑:程序博客网 时间:2024/05/01 04:48
# -*- coding: utf-8 -*-"""filename : net_csdn_bbs_topics392220754.pyauthor: hu@daonao.com QQ: 443089607 weixin: huzhenghui weibo: http://weibo.com/443089607category : abcdefgoriginal url : http://bbs.csdn.net/topics/392220754original title : python 爬虫问题title : python爬虫访问页面并显示图片csdn blog url :weibo article url :weibo message url :为了清晰直观展现python严格要求的缩进,请访问博客上博文详细说明见源代码中的注释"""# standard importimport loggingimport reimport urllibimport bs4import IPythonfrom PIL import Imageimport typinglogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')logging.debug('start')def get_html(url: str) -> str:    """    get html    """    # 访问页面    httpresponse = urllib.request.urlopen(url)    # 获取Content-Type,用于获取字符集    str_content_type = httpresponse.getheader('Content-Type')    logging.debug('str_content_type : %s', str_content_type)    pattern = re.compile(r'charset=(\S+)')    match = pattern.search(str_content_type)    # 获取字符集    str_charset = match.groups()[0]    logging.debug('str_charset : %s', str_charset)    # 获取返回字节数组    bytes_response = httpresponse.read()    # 按照字符集解码字节数组    str_response = bytes_response.decode(str_charset)    logging.debug('len(str_response) : %d', len(str_response))    return str_responsedef get_image_src(html: str) -> typing.List[str]:    """    get image src attribute    """    # 解析页面    beautifulsoup = bs4.BeautifulSoup(html, 'html5lib')    # 获取页面上所有的img标记    list_tag = beautifulsoup.select('img')    list_src = list()    for tag in list_tag:        if tag.has_attr('src') is True:            # 获取img标记的src属性            list_src.append(tag.attrs['src'])    return list_srcSTR_HTML = get_html('https://cn.bing.com/images/trending')LIST_STR_SRC = get_image_src(STR_HTML)for str_src in LIST_STR_SRC:    # 跳过data:协议    if str_src.startswith('data:'):        pass    elif str_src.startswith('/'):        # 组合URL        str_url = 'https://cn.bing.com' + str_src        # 访问URL并保存临时文件        tuple_temp = urllib.request.urlretrieve(str_url)        logging.debug(tuple_temp[0])        # 打开临时文件        image = Image.open(tuple_temp[0])        # 在IPython环境下显示图片        IPython.display.display(image)#end of file
原创粉丝点击