python之路——爬虫实例
urlController.py
import bsController
from urllib import request class SpiderMain(object):
def __init__(self):
self.header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
self.bsManage = bsController.bsManage() def getUrl(self,rootUrl):
for i in range(1,500):
url = rootUrl+'%s' %i+'.html'
req = request.Request(url)
for h in self.header:
req.add_header(h, self.header[h])
try:
html = request.urlopen(req).read()
# print(html)
self.bsManage.getPageUrl(html,i)
req.close()
except request.URLError as e:
if hasattr(e, 'code'):
print('Error code:',e.code)
elif hasattr(e, 'reason'):
print('Reason:',e.reason) if __name__=='__main__':
rootUrl = 'http://www.meitulu.com/item/'
obj_root = SpiderMain()
obj_root.getUrl(rootUrl)
bsController.py
from bs4 import BeautifulSoup
from urllib import request
import os class bsManage:
def __init__(self):
self.pageUrl = 'http://www.meitulu.com/item/'
self.header = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'} # html是获取到的网页的html
# i表示i_x.html
def getPageUrl(self,html,i):
soup = BeautifulSoup(html, 'html.parser', from_encoding='utf-8')
# 获取到最后一个连接
lastUrl = soup.find_all('div', {'id': 'pages'})[0].find_all('a')[-2]['href']
# print(html)
# print(lastUrl)
# 获取到最后一页的数字
if i < 10:
len = 1
elif i<100:
len = 2
elif i<1000:
len = 3
elif i<10000:
len = 4
lastPage = int(lastUrl[29+len:-5])
# 创建图片文件夹
if not os.path.exists('img'):
os.mkdir('img')
path = 'img/%s' %i
if not os.path.exists(path):
os.mkdir(path)
# 先爬取第一页 因为url格式不一样
# 获取所需要图片的连接 array
links = soup.find_all('img',class_='content_img')
for link in links:
name = str(link['src'])[-21:]
data = request.urlopen(link['src']).read()
img = open('img/%s/' %i + name,'wb+')
img.write(data)
img.close()
# print('%d 已经爬完' %i) # str = self.pageUrl + '%s' %i + '.html'
# print(str) # 每一个页面下有lastPage个小页面
for j in range(2,lastPage+1):
# 重新拼接url 获取到下一页的url
url = self.pageUrl + '%s_%s' %(i,j) + '.html'
self.saveImgWithUrl(url,i)
print('%d 已经爬完' %i) def saveImgWithUrl(self,url,i):
req = request.Request(url)
for h in self.header:
req.add_header(h, self.header[h])
try:
html = request.urlopen(req).read()
soup = BeautifulSoup(html, 'html.parser', from_encoding='utf-8')
# 获取所需要图片的连接 array
links = soup.find_all('img', class_='content_img')
for link in links:
name = str(link['src'])[-21:]
data = request.urlopen(link['src']).read()
img = open('img/%s/' % i + name, 'wb+')
img.write(data)
img.close()
except request.URLError as e:
if hasattr(e, 'code'):
print('Error code:', e.code)
elif hasattr(e, 'reason'):
print('Reason:', e.reason)
python之路——爬虫实例的更多相关文章
- python之路 - 爬虫
网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕 ...
- 嵩天老师python网课爬虫实例1的问题和解决方法
一,AttributeError: 'NoneType' object has no attribute 'children', 网页'tbody'没有子类 很明显,报错的意思是说tbody下面没有c ...
- python应用:爬虫实例(静态网页)
爬取起点中文网某本小说实例: # -*-coding:utf8-*- import requests import urllib import urllib2 from bs4 import Beau ...
- python应用:爬虫实例(动态网页)
以爬取搜狗图片为例,网页特点:采用“瀑布流”的方式加载图片,图片的真实地址存放在XHR中 #-*-coding:utf8-*- import requests import urllib import ...
- Python之路【第十九篇】:爬虫
Python之路[第十九篇]:爬虫 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用 ...
- Python之路【第八篇】:堡垒机实例以及数据库操作
Python之路[第八篇]:堡垒机实例以及数据库操作 堡垒机前戏 开发堡垒机之前,先来学习Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作 SSHClient ...
- Python 爬虫实例
下面是我写的一个简单爬虫实例 1.定义函数读取html网页的源代码 2.从源代码通过正则表达式挑选出自己需要获取的内容 3.序列中的htm依次写到d盘 #!/usr/bin/python import ...
- Python爬虫实例:爬取B站《工作细胞》短评——异步加载信息的爬取
很多网页的信息都是通过异步加载的,本文就举例讨论下此类网页的抓取. <工作细胞>最近比较火,bilibili 上目前的短评已经有17000多条. 先看分析下页面 右边 li 标签中的就是短 ...
- Python爬虫实例:爬取猫眼电影——破解字体反爬
字体反爬 字体反爬也就是自定义字体反爬,通过调用自定义的字体文件来渲染网页中的文字,而网页中的文字不再是文字,而是相应的字体编码,通过复制或者简单的采集是无法采集到编码后的文字内容的. 现在貌似不少网 ...
随机推荐
- 简单的FIRST+集演示程序
/* * 该程序用于计算某个非终结符的 FIRST+ 集合 * RexfieldVon * 2013年6月30日16:02:47 */ #include <stdio.h> #includ ...
- Huffman编码实现电文的转码与译码
//first thing:thanks to my teacher---chenrong Dalian Maritime university /* 构造Huffman Tree思路: ( ...
- pl sql developer登陆界面找不到oracle数据库选项
window 64位的操作系统 装的数据库win64_11gR2的数据库,PL SQL是PLSQL Developer 7.1.5最后是下载了一个instantclient_11_2包将你数据库安装路 ...
- 再看C++引用类型
之前弃用博客园的原因是其不支持markdown语法.到今天偶然进来试了一下,发现Markdown toggle原来是能支持的(不知道是不是因为它升级了),遂重新启用. 在一年前学C++的时候就对引用, ...
- poj 3478 The Stable Marriage Problem 稳定婚姻问题
题目给出n个男的和n个女的各自喜欢对方的程度,让你输出一个最佳搭配,使得他们全部人的婚姻都是稳定的. 所谓不稳婚姻是说.比方说有两对夫妇M1,F1和M2,F2,M1的老婆是F1,但他更爱F2;而F2的 ...
- Firemonkey的旁门左道[五]
这次讲讲绘制的几种模式吧,不过还是比较浅显,刚接触不久,还实在没这个实力道出个所以来. FMX下,我们可以切换GDI,D2D,GPU这三种模式, 只要通过全局变量就可以轻松搞定. 如何设置 Globa ...
- [PWA] 10. Trigger a version update
When the refersh button is clicked, we need to tell the waiting service worker to replace the curren ...
- iOS-获取UIView的全部层级结构
在iOS中获取UIView的全部层级结构 应用场景 在实际 iOS 开发中,非常多时候都须要知道某个 UI 控件中包括哪些子控件,而且分清楚它们的层级结构和自个的 frame 以及 bounds ,以 ...
- ld: 18 duplicate symbols for architecture i386 .linker command failed with exit code 1 (use -v to see invocation)_
昨天被linker这个错误卡了一个小时!!!各种办法都试了 是导入第三方的问题 .. 网上说 要把所有的.m文件导入 但是我下载的微博SDK根本不关事..后来 大概知道是导入了多个相同的文件... ...
- 应用app首次进入导航页动画
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActi ...