python----爬虫
来源:互联网 发布:淘宝线下门店有什么用 编辑:程序博客网 时间:2024/06/07 14:01
星期天看了一篇博客,就是关于一个扒取图片的爬虫,于是就学了学,现在做一点笔记,方便记忆。
这里只做一些粗略的总结。
#-*- coding:utf-8 -*-
这句是文本以utf-8编码方式
import requestsimport reurl= 'https://www.porn.com/pictures'html=requests.get(url).textpic_url=re.findall('background-image:url(.*?);',html,re.S)i=0print pic_url这两句没什么好说的,text方法保存get方法获取的内容,然后用re.findall()函数筛选出需要的内容。
运行了一下你会发现,输出的列表里面的值前面都有一个字符'u',这表示里面的字符数是用unicode编码方式,
这种编码方式是不能用string函数操作的否则就会出错。
你要是不想对每个列表中的元素进行操作的话,可以直接用的。
可能是因为运行环境的问题,我不太确定在Notepad++中是可以直接对它进行string操作的
对于unicode编码的解决方法下面会有介绍。
查看网页源码我们会发现,url之后加上主页上面图片链接的中间第三组数字就是接下来页面的网址
于是我们想办法把第三组数字筛选出来
for each in pic_url:each = each.strip('()')print eachif 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 eachif len(each) >= 60:each=str(each)try:ID=re.findall('sc/(.*?)/source',each)except:continueif ID!=[]:ID=ID[0].split(('/'))url2=url+'/'+ID[2]url2=str(url2)print url2
可以看出来我用的是split()方法将字符串用‘/’分割成三段,细节是ID是个列表,所以取出其中的唯一一个第0个元素,对其操作。之后我们就得到子页的网站链接,可以直接访问,然后下载东西。
import requestsimport reurl= 'https://www.porn.com/pictures'html=requests.get(url).textpic_url=re.findall('background-image:url(.*?);',html,re.S)i=0for 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).textpic_url2=re.findall('src="(.*?)"',html2,re.S)for each2 in pic_url2:each2 = each2.strip('()')print 'ok'if len(each2) > 50:print each2try :pic=requests.get(each2,timeout=100)except requests.exceptions.ConnectionError:print 'not ok'continuestring='F:\picture\\'+str(i)+'.jpg'fp=open(string,'wb')fp.write(pic.content)print 'ok'fp.close()i+=1
下面获取文件然后再以二进制格式保存为.jpg格式也就是content这个方法,相信一般人都是可以看懂的。代码写到这里已经结束了。下面是运行结果图
一共1902张图片,我他妈的承认这是个黄色网站,/笑哭/笑哭
有了好玩的东西不做点坏事儿怎么能行,都没意思。这个网站需要翻墙。好不多说了,最后一句话,不做宅男,少撸怡情,多撸伤身。兄弟珍重。
0 0
- python爬虫-->爬虫基础
- [爬虫] Python爬虫技巧
- Python爬虫
- python 爬虫
- python 爬虫
- python 爬虫
- python爬虫
- Python爬虫
- Python爬虫
- python 爬虫
- Python爬虫
- python爬虫
- python 爬虫
- python 爬虫
- python爬虫
- python爬虫
- python爬虫
- python 爬虫
- hihoCoder Trie 树
- A Bug's Life 分身法OR 带权并查集
- MySQL12-数据备份与还原
- Majority Element
- 《Head First Javacn》pdf
- python----爬虫
- 机器学习
- s5pv210——nandflash和inand的基础理论
- 反射(一) Reflection
- Android问题集(4):Unable to add window -- token android.os.BinderProxy@bf4921f is not valid;
- 原型模式定义
- PSR-1 (Basic Coding Standard) 基础编码标准
- ASP解析JSON格式数据方法
- 初识.net界面程序(8)——文本文件读写练习