从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请求的 ...
随机推荐
- inux下mysql的root密码忘记解决方法
1.首先确认服务器出于安全的状态,也就是没有人能够任意地连接MySQL数据库. 因为在重新设置MySQL的root密码的期间,MySQL数据库完全出于没有密码保护的 状态下,其他的用户也可以任意地登录 ...
- PAT L1 - 056 猜数字
https://pintia.cn/problem-sets/994805046380707840/problems/994805074646122496 一群人坐在一起,每人猜一个 100 以内的数 ...
- javascript 常用知识点
1:浏览器是有缓存的,开发中可以通过快捷键绕过缓存 对于Windows驱动的系统:Ctrl + F5 对于Mac驱动的系统:Command + Shift + R. 2:精度问题 (符点和大数字可能会 ...
- 第109天:Ajax请求GET和POST的区别
一.Ajax请求GET和POST的区别 1.使用Get请求时,参数在URL中显示,而使用Post方式,则不会显示出来 2.使用Get请求发送数据量小,Post请求发送数据量大 3.get请求需注意缓存 ...
- DataTable Excel 导出:
public static class CSVFileHelper { public static string ToHtmlTable(this DataTable target) { return ...
- C++解析(1):C到C++的升级
0.目录 1.C与C++的关系 2.C到C++的升级 2.1 语言的实用性 2.2 register关键字 2.3 同名的全局变量 2.4 struct关键字 2.5 int f() 与 int f( ...
- java中main函数怎么调用外部非static方法
使用外部方法时(不管是static还是非static),都要先new一个对象,才能使用该对象的方法. 举例如下: 测试函数(这是错误的): public class Test { public sta ...
- 【题解】CF#713 E-Sonya Partymaker
这题真的想了挺久的,然而到最后也还是没想到怎样处理环的情况……网上竟然也完全没有题解,无奈之下到 CF 的 AC 代码里面去找了一份膜拜了一下.感谢~ 由于觉得这题有一定的难度,自己看代码也看了比较久 ...
- 【BZOJ4651】【NOI2016】网格(Tarjan,哈希)
[BZOJ4651][NOI2016]网格(Tarjan,哈希) 题面 BZOJ 洛谷 题解 首先把题目稍微变得好说一些,给定一个网格,已经删去了若干个格子 问最少删去多少个格子使得图不连通. 这题的 ...
- 洛谷U14200 Changing 题解 【杨辉三角】
题目描述 有nnn盏灯环形排列,顺时针依次标号为1⋯n1\cdots n1⋯n.初始时刻为000,初始时刻第iii盏灯的亮灭aia_iai给定,000表示灭,111表示亮.下一时刻每盏灯的亮灭取决于 ...