网页爬虫抓取百度图片(利用python抓取网络图片的步骤:1.根据给定的网址获取)
优采云 发布时间: 2022-01-28 18:07网页爬虫抓取百度图片(利用python抓取网络图片的步骤:1.根据给定的网址获取)
使用python抓取网络图片的步骤:
1.根据给定的URL获取网页的源代码
2.使用正则表达式过滤掉源码中的图片地址
3.根据过滤后的图片地址下载网络图片
#coding=UTF-8
import urllib2
import urllib
import re
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getJpg(html):
reg = r'"largeTnImageUrl":"(.+?\.jpg)",'
imgre = re.compile(reg)
imglist = re.findall(imgre, html)
x = 0
for imgurl in imglist:
print imgurl
#urllib.urlretrieve(imgurl, 'D:/test/%s.html' % x)
header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept':'text/html;q=0.9,*/*;q=0.8',
'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding':'gzip',
'Connection':'close',
'Referer':'http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1425134407244_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E6%AF%94%E5%9F%BA%E5%B0%BC%E7%BE%8E%E5%A5%B3&f=3&oq=b&rsp=-1'
}
timeout = 30
request = urllib2.Request(imgurl,None,header)
response = urllib2.urlopen(request,None,timeout)
str = response.read()
foo = open("D:/test/%s.gif" % x,"wb")
foo.write(str)
foo.close()
x += 1
html = getHtml('http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1425134407244_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E6%AF%94%E5%9F%BA%E5%B0%BC%E7%BE%8E%E5%A5%B3&f=3&oq=b&rsp=-1')
print getJpg(html)
博客示例参考:
在参考博客实现示例的过程中,我也遇到了一些问题。图片已下载,但无法预览。经过多次分析,发现百度图片设置了反爬。为了解决这个问题,我参考了另一篇博文。
模拟浏览器发送请求并欺骗服务器进行反爬: