爬取百度logo

#!/usr/bin/env python3

# _*_ coding:utf-8 _*_

import logging,shutil,os,requests

from bs4import BeautifulSoup

from selenium.webdriver.supportimport expected_conditions

#查找baidu,并保存到当前文件夹下

url="https://www.baidu.com"

logging.basicConfig(level=logging.INFO)

headers={}

headers['User-Agent']="Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"

# 发送get请求获得一个response对象(我们可以从响应对象获得我们想要的一切数据),requests 会自动帮我们拼接请求地址

res=requests.get(url,headers=headers)

try:

if res.status_code==200:

# html字符串创建BeautifulSoup对象

        soup=BeautifulSoup(res.text,'html.parser')#html解析器

#输出网页内容

        print(soup.prettify())

#print ("以上网页内容")

#img_logo=soup.select_one("head > title")#返回list首位

        img_logo = soup.select_one('#lg > img.index-logo-src')

#img_log=select.xpath("//*[@id="lg"]/img[1]")

        print ("img_logo"+str(img_logo))

if img_logo:

print("aaa")

img_url=img_logo["src"]#返回图片标签的src属性

#组合成完整的url

            img_url=img_urlif img_url.startswith("http")else "http:"+img_url

print (img_url)

#先删除本地,在下载

            file_name="logo.png"

            if os.path.isfile(file_name):

os.remove(file_name)

#获取图片数据流

            res=requests.get(img_url,stream=True)

with open(file_name,"wb")as out_file:

shutil.copyfileobj(res.raw,out_file)

print ("ssd")

else:

logging.info("查找元素失败")

else:

logging.info("请求失败")

except WindowsError:

logging.info("连接错误")


#注意url正确,且头文件正确;

#可使用命令行直接运行 pypthon pc2.py  ,若没有导入相关包使用pip install  bs4 命令导入

#注销一大块使用快捷键ctl+/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Date:2016-9-21update:2016-9-30By:Black Crow 前言: 终于进入到网络页面...
    black_crow阅读 878评论 0 2
  • 声明:本文讲解的实战内容,均仅用于学习交流,请勿用于任何商业用途! 一、前言 强烈建议:请在电脑的陪同下,阅读本文...
    Bruce_Szh阅读 12,768评论 6 28
  • 珍宝岛,一个依然那么熟悉的名字。那年代在小学教科书里,在电影记录片中,珍宝岛就已经深深植入我们小时心里。虽然已经过...
    宗玉兰阅读 556评论 0 1
  • 2016.11.29 这就是我的晚餐,咖啡是买面条送的。具体说是办理会员,每次吃饭就可以喝免费的热饮。 办理会员的...
    碳哥哥阅读 674评论 4 23
  • 你伪装成万兽之王 露出你的虎牙光亮耀眼 引诱我探险 你的爱沉溺在森林的幽深中 迷茫得四处飘洒 你的爱沉溺在情人们的...
    雨格格君阅读 530评论 0 1