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基础到一个简单抓取网页图片的小爬虫的更多相关文章

  1. Python3简单爬虫抓取网页图片

    现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2), 所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到 ...

  2. java爬虫-简单爬取网页图片

    刚刚接触到“爬虫”这个词的时候是在大一,那时候什么都不明白,但知道了百度.谷歌他们的搜索引擎就是个爬虫. 现在大二.再次燃起对爬虫的热爱,查阅资料,知道常用java.python语言编程,这次我选择了 ...

  3. Python -- 网络编程 -- 简单抓取网页

    抓取网页: urllib.request.urlopen(url).read().decode('utf-8')  ---  (百度是utf-8,谷歌不是utf-8,也不是cp936,ascii也不行 ...

  4. 30分钟编写一个抓取 Unsplash 图片的 Python爬虫

       我一直想用 Python and Selenium 创建一个网页爬虫,但从来没有实现它. 几天前, 我决定尝试一下,这听起来可能是挺复杂的, 然而编写代码从 Unsplash 抓取一些美丽的图片 ...

  5. [Python]网络爬虫(六):一个简单的百度贴吧的小爬虫

    转自:http://blog.csdn.net/pleasecallmewhy/article/details/8927832 # -*- coding: utf-8 -*- #----------- ...

  6. python 简单抓取网页并写入excel实例

    # -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup import xlwt import time #获取第一页 ...

  7. JMeter基础之一 一个简单的性能测试

    JMeter基础之一 一个简单的性能测试 上一节中,我们了解了jmeter的一此主要元件,那么这些元件如何使用到性能测试中呢.这一节创建一个简单的测试计划来使用这些元件.该计划对应的测试需求. 1)测 ...

  8. C语言Linix服务器网络爬虫项目(二)项目设计和通过一个http请求抓取网页的简单实现

    我们通过上一篇了解了爬虫具体要实现的工作之后,我们分析得出的网络爬虫的基本工作流程如下: 1.首先选取一部分精心挑选的种子URL: 2.将这些URL放入待抓取URL队列: 3.从待抓取URL队列中取出 ...

  9. [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容

    版本号:Python2.7.5,Python3改动较大. 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 类似于使用程序模拟IE浏览器的功能,把URL作为HTTP请求的 ...

随机推荐

  1. mysql(四)log

    慢查询: https://blog.csdn.net/leshami/article/details/39829605 日志组成: https://blog.csdn.net/leshami/arti ...

  2. JSON字符串转换成对象时候 需要有默认构造器 因为这是通过反射创建的 反射是先通过默认构造器创建对象的

    JSON字符串转换成对象时候 需要有默认构造器 因为这是通过反射创建的 反射是先通过默认构造器创建对象的

  3. bzoj2788-Festival

    题意 有 \(n\) 个变量,有两种限制,分别有 \(m_1,m_2\) 种.限制如下: \(a_x+1=a_y\) \(a_x\le a_y\) 求 \(\{x_i\}\) 集合的大小.\(n\le ...

  4. Django 2.0 学习(17):Django 用户认证(auth模块)

    Django 用户认证(auth模块) 一.认证登陆 在进行用户登陆验证的时候,如果是自己写代码,就必须要先查询数据库,看用户输入的用户名是否存在于数据库中:如果用户存在于数据库中,然后再验证用户输入 ...

  5. 插件-3D轮播图

    先上效果图 查看实例点击 这里  这个栗子中,可以选择展示 5 张 或者展示 3 张,即使是只有一个slide,也可以完成布局,正常轮播,麻麻再也不用怕只有4个slid而不能用这种轮播啦! 本栗实现原 ...

  6. BZOJ3566 SHOI2014概率充电器(动态规划+概率期望)

    设f[i]为i在子树内不与充电点连通的概率.则f[i]=(1-pi)·∏(1-qk+qk·f[k]). 然后从父亲更新答案.则f[i]=f[i]·(1-qfa+qfa*f[fa]/(1-qfa+qfa ...

  7. P2475 [SCOI2008]斜堆

    题目背景 四川2008NOI省选 题目描述 斜堆(skew heap)是一种常用的数据结构.它也是二叉树,且满足与二叉堆相 同的堆性质:每个非根结点的值都比它父亲大.因此在整棵斜堆中,根的值最小. 但 ...

  8. Bond UVA - 11354(并查集按秩合并)

    题意: 给你一张无向图,然后有若干组询问,让你输出a->b的最小瓶颈路. 解析: 应该都想过用prime的次小生成树做..但二维数组开不了那么大..所以只能用kruskal了.... #incl ...

  9. CF1093F Vasya and Array DP

    题面 题面 \(\Delta\)题面有点问题,应该是数列中没有长度大于等于\(len\)的连续数字才是合法的. 题解 设\(f[i][j]\)表示DP到\(i\)位,以\(j\)为结尾的方案数, \( ...

  10. 【BZOJ1492】【NOI2007】货币兑换(动态规划,CDQ分治,Splay)

    [BZOJ1492][NOI2007]货币兑换(动态规划,CDQ分治,Splay) 题面 BZOJ 洛谷 Description 小Y最近在一家金券交易所工作.该金券交易所只发行交易两种金券:A纪念券 ...