python爬取图片代码可替换网站_python爬取网站图片

这篇博客介绍了作者利用Python的lxml库爬取网页图片的过程。首先,作者讲述了lxml和BeautifulSoup的区别,强调lxml在处理数据上的高效性。接着,展示了如何通过lxml的xpath定位图片链接,并通过递归获取图片的完整URL。最后,代码实现了下载图片并保存的功能。整个过程详细记录了从获取网页链接、解析HTML到保存图片的步骤。
摘要由CSDN通过智能技术生成

周末自己花时间看了一下python爬取网络图片的一些实例,自己动手也操作了一下。

算是记录一些知识点。

Python爬取网站信息有lxml和beautifulsoup这两个库。具体beautifulsoup可以很好的处理不规范的标记并生成剖析,是用python写的一个html/xml的解析器。提供简单又常用的导航,搜索及修改剖析树的操作。Lxml是python语言里和xml以及html工作的功能最丰富和最容易使用的库。Lxml利用元素遍历法来处理数据,而不是像beautifulsoup一样利用正则表达式来提取数据,提供的xpth功能可以更方便定位元素。我使用的是lxml,只是简单的使用了它的xpath定位功能,具体的其他功能还有待挖掘,api网址:http://lxml.de/

参考网址:http://blog.csdn.net/betabin/article/details/24392369

http://www.th7.cn/Program/Python/201602/764736.shtml

Lxml下载地址:https://pypi.python.org/pypi/lxml/3.4.4#downloads 直接下载exe文件安装,以减少各种不必要的麻烦。

通过分析网站链接地址可以清楚每个图片页的链接,将这些请求的链接放到list中:

baseurl="http://www.immtb.com/xiaohua/2015/0916/39_"

urls=[]

for i in range(2,6):

urls.append(baseurl+str(i)+".html")

然后分别访问这个list中的链接。

response=requests.get(url,headers=self.headers)  #headers表示自己是哪个浏览器

html=response.content   #content表示得到源码的内容

Page=etree.HTML(html.lower().decode(‘utf-8’))   #lxml必须进行编码转换

附上完整代码:

#!usr/bin/python

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

import re

import requests

from lxml import html

from lxml import etree

import sys

import os

'''

仅仅是练手,转载请注明出处

'''

class Pics(object):

user_agent = 'Mozilla/5.0 (compatible; MSIE 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36'

headers = {'User-Agent':user_agent}

mypicurls=[]

mypicname=[]

listdigui=[]

#原始四条url

def getpicUrl(self):

baseurl="http://www.immtb.com/xiaohua/2015/0916/39_"

urls=[]

for i in range(2,6):

urls.append(baseurl+str(i)+".html")

#print urls

for url in urls:

responsing=requests.get(url,headers=self.headers)

#print responsing

html=responsing.content     #得到网页的源代码内容

#print html

page=etree.HTML(html.lower().decode('utf-8'))

#hs=page.xpath(u"//p")

#print hs[0].text

images=page.xpath(u"//*[@id='showimg']/a/img")

for i in images:

print i.attrib     #表示得到这个xpath中的 属性值

#print i.text   #表示得到这个xpath中的值

#print str(i.attrib)

aa=dict(i.attrib)        #转换成字典类型,可以查找其中的src所代表的图片地址

#print type(aa)

print aa['src']

myimageurl=aa['src']

self.digui(myimageurl)   #通过递归得到图片的名字

print self.listdigui[-1]   #图片最终保存名字

self.mypicname.append(self.listdigui[-1]) #将得到的图片的文件名称添加到list中去

self.mypicurls.append(myimageurl)    #将得到的image链接填到list中去

#cc='http://www.immtb.com/xiaohua/2015/0916/39_'

def digui(self,c):

z=c.find("/")

if z!=-1 :

self.listdigui.append(c[0:z])

c=c[z+1:]

self.digui(c)

else:

self.listdigui.append(c)

#digui(cc)

#print listdigui

def mypicdirs(self):

filedir="D:/test/meitu/"

if not os.path.exists(filedir):

os.makedirs(os.path.join('D:/','test','meitu'))

return filedir

def savemyimg(self):

self.getpicUrl()

dirs=self.mypicdirs()

leng=len(self.mypicurls)

for i in range(0,leng):

try:

uris=requests.get(self.mypicurls[i],headers=self.headers,stream=True)

myimagepic=open(dirs+self.mypicname[i],"wb")

myimagepic.write(uris.content)

except Exception,e:

print e

if __name__=="__main__":

Pics().savemyimg()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值