python----爬虫

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36278071/article/details/72084841

星期天看了一篇博客,就是关于一个扒取图片的爬虫,于是就学了学,现在做一点笔记,方便记忆。

这里只做一些粗略的总结。

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

这句是文本以utf-8编码方式

 
 

import requests
import re


url= 'https://www.porn.com/pictures'
html=requests.get(url).text
pic_url=re.findall('background-image:url(.*?);',html,re.S)


i=0
print pic_url
 
 

这两句没什么好说的,text方法保存get方法获取的内容,然后用re.findall()函数筛选出需要的内容。

运行了一下你会发现,输出的列表里面的值前面都有一个字符'u',这表示里面的字符数是用unicode编码方式,

这种编码方式是不能用string函数操作的否则就会出错。

你要是不想对每个列表中的元素进行操作的话,可以直接用的。

可能是因为运行环境的问题,我不太确定在Notepad++中是可以直接对它进行string操作的

对于unicode编码的解决方法下面会有介绍。


查看网页源码我们会发现,url之后加上主页上面图片链接的中间第三组数字就是接下来页面的网址

于是我们想办法把第三组数字筛选出来


for each in pic_url:
	each = each.strip('()')
	print each
	if len(each) >= 60:
		each=str(each)
		try:
		
			ID=re.findall('sc/(.*?)/source',each)
		except:
			continue
正则表达式没学好我按照'background-image:url(.*?);'的筛选方式,筛选出来的列表元素都带有一对括号,
用strop()删除开头和结尾的括号

之后是筛选出进入下一页的链接(也就是长度大于60的链接)

将为unicode编码的each强行转化成字符串这样会有个问题每个字符串

for each in pic_url:
	each = each.strip('()')
	print each
	if len(each) >= 60:
		each=str(each)
		try:
		
			ID=re.findall('sc/(.*?)/source',each)
		except:
			continue
		if ID!=[]:
			
			ID=ID[0].split(('/'))
			
			
			
			
			
			url2=url+'/'+ID[2]
			url2=str(url2)
			print url2

可以看出来我用的是split()方法将字符串用‘/’分割成三段,细节是ID是个列表,所以取出其中的唯一一个第0个元素,对其操作。

之后我们就得到子页的网站链接,可以直接访问,然后下载东西。


import requests
import re


url= 'https://www.porn.com/pictures'
html=requests.get(url).text
pic_url=re.findall('background-image:url(.*?);',html,re.S)


i=0
for each in pic_url:
	each = each.strip('()')
	
	if len(each) >= 60:
		each=str(each)
		ID=re.findall('sc/(.*?)/source',each)
		if ID!=[]:
			ID=ID[0].split(('/'))
			
			url2=url+'/'+str(ID[2])
		
			html2=requests.get(url2).text
			pic_url2=re.findall('src="(.*?)"',html2,re.S)
			for each2 in pic_url2:
				each2 = each2.strip('()')
				print 'ok'
				if len(each2) > 50:
					print each2
					try :
						pic=requests.get(each2,timeout=100)
					except requests.exceptions.ConnectionError:
						print 'not ok'
						continue
					string='F:\picture\\'+str(i)+'.jpg'
					fp=open(string,'wb')
					fp.write(pic.content)
					print 'ok'
					fp.close()
					i+=1

下面获取文件然后再以二进制格式保存为.jpg格式也就是content这个方法,相信一般人都是可以看懂的。

代码写到这里已经结束了。下面是运行结果图



一共1902张图片,我他妈的承认这是个黄色网站,/笑哭/笑哭

有了好玩的东西不做点坏事儿怎么能行,都没意思。这个网站需要翻墙。好不多说了,最后一句话,不做宅男,少撸怡情,多撸伤身。兄弟珍重。


猜你喜欢

转载自blog.csdn.net/qq_36278071/article/details/72084841