Python抓取百度图片

从百度上采集内容的时候,如果能够附上一张图片,将是非常不错的。图文并茂,比单调的文字,无论从排名还是用户体验来讲,都会好一些。

下面跟大家分享一段python代码,能够根据关键字,采集wap.baidu.com上的第一张图片。


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

from urllib import FancyURLopener
import urllib,urllib2
import time
import os
import sys
from BeautifulSoup import BeautifulSoup


def download(link):
    try:
        data = urllib.urlopen(link).read()
    except Exception,e:
        return False            
    file_name = str(int(time.time()))+'.jpg'
    file_path = os.path.join("images/",file_name)
    image = open(file_path,'wb')
     
    try:               
        image.write(data)
    except Exception,e:
        return False
    image.close()
    return True

keyword = 'SEO'
URL="http://image.baidu.com/i?tn=wisemiddetail&ie=utf8&word=%s&fmpage=detail&pn=2&size=mid&pos=next" % keyword
print URL

opener = urllib.FancyURLopener({})
opener.addheaders = [('User-agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]                             
f = opener.open(URL)
htmlstr = f.read()

soup = BeautifulSoup(htmlstr,fromEncoding="GBK")

titleinfo = soup.findAll('div',{'class':'ct'})                 

for k in titleinfo:
    urlcache = k('img')[0]['src']
    print urlcache
    print download(urlcache)

只是实现了最基本的根据关键字下载百度第一张图片的功能,结合采集百度网页内容的代码,能够实现图文并茂的采集。如果加入循环功能,就可以根据关键字列表,实现批量的采集图文并茂的页面。наращивание костной ткани при имплантации отзывыдля винтовых

1 thought on “Python抓取百度图片

Leave a Comment