从urllib和urllib2基础到一个简单抓取网页图片的小爬虫
urllib最常用的两大功能(个人理解urllib用于辅助urllib2)
1.urllib.urlopen()
2. urllib.urlencode() #适当的编码,可用于后面的post提交数据
import urllib
Dict = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python'}
print urllib.urlencode(Dict)
urllib2常用的函数
1.最基本的打开读取一个网页
import urllib2
response = urllib2.urlopen('http://www.baidu.com/')
html = response.read()
2.地址创建一个Request对象
req = urllib2.Request('http://www.baidu.com/')
response = urllib2.urlopen(req)
the_page = response.read()
3.Data数据利用post方式提交
value={'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python'}
data = urllib.urlencode(values)
request = urllib2.Request(url,data)
#request= urllib2.Request(url, data, headers) Request对象共有三个参数
response = urllib2.urlopen(request)
print response.read()
4.在 HTTP Request 中加入特定的 Header
import urllib2
request = urllib2.Request('http://www.baidu.com/')
request.add_header('User-Agent', 'fake-client')
response = urllib2.urlopen(request)
print response.read()
5.Cookie
import urllib2
import cookielib
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open('http://www.baidu.com')
for item in cookie:
print 'Name = '+item.name
print 'Value = '+item.value
6.得到 HTTP 的返回码
import urllib2
try:
response = urllib2.urlopen('http://bbs.csdn.net/why')
except urllib2.HTTPError, e:
print e.code
7.Timeout 设置
import urllib2
response = urllib2.urlopen('http://www.baidu.com/', timeout=10)
8.Redirect动作
import urllib2
my_url = 'http://www.google.cn'
response = urllib2.urlopen(my_url)
redirected = response.geturl() == my_url
print redirected
my_url = 'http://rrurl.cn/b1UZuP'
response = urllib2.urlopen(my_url)
redirected = response.geturl() == my_url
print redirected
9.使用 HTTP 的 PUT 和 DELETE 方法
import urllib2
request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'PUT' # or 'DELETE'
response = urllib2.urlopen(request)
10.Debug Log
import urllib2
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler, httpsHandler)
urllib2.install_opener(opener)
response = urllib2.urlopen('http://www.google.com')
11.表单的处理
# -*- coding: utf-8 -*-
import urllib
import urllib2
postdata=urllib.urlencode({
'username':'汪小光',
'password':'why888',
'continueURI':'http://www.verycd.com/',
'fk':'',
'login_submit':'登录'
})
req = urllib2.Request(
url = 'http://secure.verycd.com/signin',
data = postdata
)
result = urllib2.urlopen(req)
print result.read()
最后附上一段抓取某网站妹子图片的代码
import urllib
import urllib2
import os def url_open(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0')
response = urllib2.urlopen(req)
html = response.read() return html def get_page(url):
html = url_open(url).decode('utf-8') a = html.find('current-comment-page') + 23
b = html.find(']', a) return html[a:b] def find_imgs(url):
html = url_open(url).decode('utf-8')
img_addrs = [] a = html.find('img src=') while a != -1:
b = html.find('.jpg', a, a+255)
if b != -1:
img_addrs.append(html[a+9:b+4])
else:
b = a + 9 a = html.find('img src=', b) return img_addrs def save_imgs(folder, img_addrs):
for each in img_addrs:
filename = each.split('/')[-1]
with open(filename, 'wb') as f:
img = url_open(each)
f.write(img) def download_mm(folder='OOXX', pages=10):
os.mkdir(folder)
os.chdir(folder) url = "http://jandan.net/ooxx/"
page_num = int(get_page(url)) for i in range(pages):
page_num -= i
page_url = url + 'page-' + str(page_num) + '#comments'
img_addrs = find_imgs(page_url)
save_imgs(folder, img_addrs) if __name__ == '__main__':
download_mm()
从urllib和urllib2基础到一个简单抓取网页图片的小爬虫的更多相关文章
- Python3简单爬虫抓取网页图片
现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2), 所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到 ...
- java爬虫-简单爬取网页图片
刚刚接触到“爬虫”这个词的时候是在大一,那时候什么都不明白,但知道了百度.谷歌他们的搜索引擎就是个爬虫. 现在大二.再次燃起对爬虫的热爱,查阅资料,知道常用java.python语言编程,这次我选择了 ...
- Python -- 网络编程 -- 简单抓取网页
抓取网页: urllib.request.urlopen(url).read().decode('utf-8') --- (百度是utf-8,谷歌不是utf-8,也不是cp936,ascii也不行 ...
- 30分钟编写一个抓取 Unsplash 图片的 Python爬虫
我一直想用 Python and Selenium 创建一个网页爬虫,但从来没有实现它. 几天前, 我决定尝试一下,这听起来可能是挺复杂的, 然而编写代码从 Unsplash 抓取一些美丽的图片 ...
- [Python]网络爬虫(六):一个简单的百度贴吧的小爬虫
转自:http://blog.csdn.net/pleasecallmewhy/article/details/8927832 # -*- coding: utf-8 -*- #----------- ...
- python 简单抓取网页并写入excel实例
# -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup import xlwt import time #获取第一页 ...
- JMeter基础之一 一个简单的性能测试
JMeter基础之一 一个简单的性能测试 上一节中,我们了解了jmeter的一此主要元件,那么这些元件如何使用到性能测试中呢.这一节创建一个简单的测试计划来使用这些元件.该计划对应的测试需求. 1)测 ...
- C语言Linix服务器网络爬虫项目(二)项目设计和通过一个http请求抓取网页的简单实现
我们通过上一篇了解了爬虫具体要实现的工作之后,我们分析得出的网络爬虫的基本工作流程如下: 1.首先选取一部分精心挑选的种子URL: 2.将这些URL放入待抓取URL队列: 3.从待抓取URL队列中取出 ...
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
版本号:Python2.7.5,Python3改动较大. 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 类似于使用程序模拟IE浏览器的功能,把URL作为HTTP请求的 ...
随机推荐
- 【leetcode】215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the so ...
- TP中CURD操作
CURD操作 CURD操作也就是模型操作数据表的基本操作.C(Create).U(Update).R(Read).D(Delete)操作就是增删改查操作. 6.1.增加操作 回想一下在mysql中增加 ...
- 【UNIX环境高级编程】线程同步
当多个线程共享相同的内存时,需要确保每个线程看到一致的数据视图.如果每个线程使用的变量都是其他线程不会读取和修改的,那么就不存在一致性问题.同样,如果变量是只读的也不会有一致性问题.但是,当一个线程可 ...
- LoadRunner录制用户操作
先说明一点,使用录制的手段拿到的测试脚本和工程师自己编写的测试脚本其实是一样的,不要觉得录制的方式low,而自己编写脚本就显得高大上,这是不对的.除非工程师本身对开发们写的代码逻辑很熟,对业务上的各个 ...
- 【Python】第一篇:python基础_1
本篇内容 Python介绍 安装 第一个程序(hello,world) 变量 用户输入(input) 数据类型 数据运算 if判断 break和continue的区别 while 循环 一. Pyth ...
- P2812 校园网络【[USACO]Network of Schools加强版】
题目背景 浙江省的几所OI强校的神犇发明了一种人工智能,可以AC任何题目,所以他们决定建立一个网络来共享这个软件.但是由于他们脑力劳动过多导致全身无力身体被♂掏♂空,他们来找你帮助他们. 题目描述 共 ...
- 洛谷 P2888 [USACO07NOV]牛栏Cow Hurdles
题目戳 题目描述 Farmer John wants the cows to prepare for the county jumping competition, so Bessie and the ...
- 【MediaElement】WPF视频播放器【1】
一.前言 前两天上峰要求做一个软件使用向导,使用WPF制作.这不,这两天从一张白纸开始学起,做一个播放演示视频的使用向导.以下是粗设计的原型代码: 二.效果图 三.代码 前台代码: < ...
- python实现RSA加解密
# coding=utf-8 """ @author:Eleven created on:2018年10月30日 """ import bi ...
- Redis Scan迭代器遍历操作原理(二)
续上一篇文章 Redis Scan迭代器遍历操作原理(一)–基础 ,这里着重讲一下dictScan函数的原理,其实也就是redis SCAN操作最有价值(也是最难懂的部分). 关于这个算法的源头,来自 ...