#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import logging,shutil,os,requests
from bs4import BeautifulSoup
from selenium.webdriver.supportimport expected_conditions
#查找baidu,并保存到當(dāng)前文件夾下
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"
# 發(fā)送get請(qǐng)求獲得一個(gè)response對(duì)象(我們可以從響應(yīng)對(duì)象獲得我們想要的一切數(shù)據(jù)),requests 會(huì)自動(dòng)幫我們拼接請(qǐng)求地址
res=requests.get(url,headers=headers)
try:
if res.status_code==200:
# html字符串創(chuàng)建BeautifulSoup對(duì)象
? ? ? ? soup=BeautifulSoup(res.text,'html.parser')#html解析器
#輸出網(wǎng)頁(yè)內(nèi)容
? ? ? ? print(soup.prettify())
#print ("以上網(wǎng)頁(yè)內(nèi)容")
#img_logo=soup.select_one("head > title")#返回list首位
? ? ? ? img_logo = soup.select_one('#lg > img.index-logo-src')
#img_log=select.xpath("http://*[@id="lg"]/img[1]")
? ? ? ? print ("img_logo"+str(img_logo))
if img_logo:
print("aaa")
img_url=img_logo["src"]#返回圖片標(biāo)簽的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)
#獲取圖片數(shù)據(jù)流
? ? ? ? ? ? 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("請(qǐng)求失敗")
except WindowsError:
logging.info("連接錯(cuò)誤")
#注意url正確,且頭文件正確;
#可使用命令行直接運(yùn)行 pypthon pc2.py? ,若沒(méi)有導(dǎo)入相關(guān)包使用pip install? bs4 命令導(dǎo)入
#注銷(xiāo)一大塊使用快捷鍵ctl+/