1. 背景
- Bing搜索每天的背景圖片有些比較適合做桌面,但是有的提供下載有的不提供下載。每天去點擊下載又不太方便,所以第一次學習了一下python爬蟲怎么寫,寫的很簡單。
2. 相關技術
2.1 Python爬蟲參考
2.2 Python正則表達式
2.3 解決登錄問題
2.4 logging:內置日志庫
3. 爬蟲實現
- 爬蟲分三個部分:請求,解析,保存。
- 下面只展示主要邏輯代碼。完整代碼參考Github。
3.1 請求腳本
import urllib.request
import re
import logging
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
if html:
logging.debug("Get Response:"+str(len(html)))
else:
logging.warning("Request failed!")
return html.decode('utf-8')
3.2 解析腳本
- 重點是解析腳本,這里定義了兩種方法:一種通過正則表達式匹配,另一種使用BeautifulSoup解析文檔樹。通過文檔書解析是原來通過下載頁面來解析的,但是發現下載的頁面與直接請求http://cn.bing.com/獲得的響應是不同的,因為有js腳本做了后續處理。所以無法做爬蟲解析。只能使用了正則表達式匹配,效果還好。
from bs4 import BeautifulSoup
import json
import re
import logging
def getJpg(html):
reg = r'(url:.{10,90}jpg)' //這里匹配包含"url:**jpg"的字符串,沒寫出更精確的正則表達式,只能寫匹配10到90個字符了
logging.debug("Using re "+reg+" to get Jpg")
jpgre= re.compile(reg)
jpglist=re.findall(jpgre,html)
if jpglist:
logging.debug("Get jpg list("+str(len(jpglist))+"):"+str(jpglist))
jpgUrl = jpglist[0].split('"')[1]
imageUrl = host+jpgUrl
logging.info("Get jpg url:"+imageUrl)
return imageUrl
def bingParser(html):
#soup=BeautifulSoup(html,"html.parser")//直接解析響應就會有問題獲取不到
soup=BeautifulSoup(open('Bing.html'),"html.parser") //最初通過下載的頁面解析成功
print(soup.title)
print(type(soup.a))
print(soup.select('#bgDiv'))
style = (soup.select('#bgDiv')[0].attrs['style']).strip()
print(style)
json_style=json.dumps(style)
print(json_style)
imageurl=style.strip().split(';')[-3:-2]
#print(imageurl[0].split('"')[1])
imageUrl = (imageurl[0].split('"')[1])
#imageUrl = (imageurl[0].split(':')[1].strip().split('"')[1])
print(imageUrl)
return imageUrl
3.3 保存腳本
- 保存腳本是需要運行的腳本,所以其他腳本都在這里調用了。
import urllib.request
import urllib.parse
import parseHtml
import request
import logging
import sys
//定義日志
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='bingcn.log',
filemode='a'
)
host="http://cn.bing.com"
logging.info("From:"+host)
html = request.getHtml(host)
imageurl = parseHtml.getJpg(html)
logging.info("Image url:"+imageurl)
fileName = imageurl.split('/')[-1:][0]
logging.info("Image file name:"+fileName)
def saveImg(imageURL,fileName):
url = (imageURL)
logging.info('Image file url:'+url)
#url=urllib.parse.urlencode(url)
u = urllib.request.urlopen(url)
data = u.read()
f = open(fileName, 'wb')
f.write(data)
logging.info("Save file :"+imageURL)
f.close()
saveImg(imageurl,fileName)
4. 運行
- 腳本針對python3環境寫的,直接運行saveImage.py即可。
- 如果使用日志文件的方式,可以在當前目錄下看到日志文件bingcn.log,保存的圖片也在當前目錄下。
james@james:~/code/hello-world/code/python/networkong/pycrowler/crowler_bingcn > python3 saveImage.py
2017-06-26 14:36:05 saveImage.py[line:19] INFO From:http://cn.bing.com
2017-06-26 14:36:06 request.py[line:12] DEBUG Get Response:126510
2017-06-26 14:36:06 parseHtml.py[line:91] DEBUG Using re (url:.{10,90}jpg) to get Jpg
2017-06-26 14:36:06 parseHtml.py[line:95] DEBUG Get jpg list(2):['url: "/az/hprichbg/rb/MadagascarLemurs_ZH-CN7754035615_1920x1080.jpg', "url:'\\/az\\/hprichbg\\/rb\\/CallanishSS_ZH-CN12559903397_1920x1080.jpg"]
2017-06-26 14:36:06 parseHtml.py[line:98] INFO Get jpg url:http://cn.bing.com/az/hprichbg/rb/MadagascarLemurs_ZH-CN7754035615_1920x1080.jpg
2017-06-26 14:36:06 saveImage.py[line:24] INFO Image url:http://cn.bing.com/az/hprichbg/rb/MadagascarLemurs_ZH-CN7754035615_1920x1080.jpg
2017-06-26 14:36:06 saveImage.py[line:26] INFO Image file name:MadagascarLemurs_ZH-CN7754035615_1920x1080.jpg
2017-06-26 14:36:06 saveImage.py[line:30] INFO Image file url:http://cn.bing.com/az/hprichbg/rb/MadagascarLemurs_ZH-CN7754035615_1920x1080.jpg
2017-06-26 14:36:06 saveImage.py[line:36] INFO Save file :http://cn.bing.com/az/hprichbg/rb/MadagascarLemurs_ZH-CN7754035615_1920x1080.jpg