Python爬虫框架
本文章的源代码来源于https://github.com/Holit/Web-Crawler-Framwork
一、爬虫框架的代码
import urllib.request
from bs4 import BeautifulSoup
import re
import time
import _thread # Input your Url here####################################
BaseURL = '127.0.0.1/'
#########################################################
TaxURL = ".html" #Input your data-saving path ############################
SavePath = ""
######################################################### #Input your threads count ###############################
thread_count = 1
######################################################### #Set each spider will spy how many pages ################
thread_spy_count_ench = 5
#########################################################
def mkdir(path):
# Create the directory
import os
path=path.strip()
path=path.rstrip("\\")
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
return True
else:
return False def download(start, count):
#Spider main
for i in range(start,start + count):
try:
#DEBUG##################################################
#print("[INFO] Connecting to page #" + str(i) + "...")
######################################################## #Used to record time
time_start=time.time() #Construct url
#This only work like
# https://127.0.0.1/articles/00001.html
# https://127.0.0.1/articles/00002.html
# https://127.0.0.1/articles/00003.html
TargetURL = BaseURL + str(i) + TaxURL #create Request object
req = urllib.request.Request(TargetURL)
#create headers using general header, you could find this by Fiddler(R) or by Chrome(R)
req.add_header('Host','') #Your Host, usally set as url-base
req.add_header('Referer',TargetURL) #Your Referer, usally set as url
req.add_header('User-Agent', 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19')
#finishing create Request object #get information
res = urllib.request.urlopen(req)
#decode the html
soup = BeautifulSoup(res,"html.parser")
##############################################################
#add your functions here.... #operate_data(data) #soup find div to get inforamtion.
#soup is able to opreate html tag very easily, by using soup.find(...)
############################################################## #Change saving path here.
savetarget = SavePath #trying to saving files
try:
#create directory if it doesn't existed
mkdir(SavePath+"\\"+str(zone)+"\\")
#using open...
f = open(savetarget,'w') #edit this
f.write("data") except Exception as e:
time_end=time.time()
print(" [Failed] - #" + str(i) + " Error : " + str(e))
else: time_end=time.time()
print(" [Succeed] - #" + str(i) + " has saved to path.("+str(time_end-time_start)+"s)") pass
except Exception as e:
print(" [Global Failure] - #" + str(i) + " Error : " + str(e))
pass #if __name__ == __main__:
try:
#Multithreading
print("Spidering webiste...")
print("Current configuration :")
print("--Will create " + str(thread_count) + "threads to access.")
print("--Will save to " + SavePath)
print("-------------START---------------------------")
# press any key to continue
# this won't work under linux
import os
os.system('pause')
try:
for i in range(0,thread_count):
print("[Thread #"+ str (i) +"] started successfully")
_thread.start_new_thread(download, (thread_spy_count_ench * i,thread_spy_count_ench))
except Exception as e:
print("[Threading@" + str(i) +"] Error:"+ str(e))
except Exception as e:
print("[Global Failure] Error:"+ str(e))
while 1:
pass
二、对其中功能的实例化操作
1.文本获取功能
文本获取是指对页面的<div class='content'>...</div>中的内容进行获取,这是前提。如果不同需要更改。
(1)思路
使用BeautifulSoup对html分析之后得到解码的文件,例如
<div class="content" style="text-align: left">
基础内容
</div>
现在对该段落进行选取,即使用soup.find功能
(2)基本代码
passages_div = soup.find('div')
passages_set = passages_div.findAll(attrs={"class":"content"})
for passages in passages_set:
article = str(passages)
#文字处理
article = article.replace('<div class="content" style="text-align: left">', '')
article = article.replace(u'\ue505', u' ')#对Unicode的空格进行处理,如果不处理gbk无法编码
article = article.replace(u'\ue4c6', u' ')
article = article.replace(u'\xa0', u' ')
article = article.replace('<br/>', '\n')
article = article.replace('</div>', '')
savetarget = 'D:\test\test.txt'
try:
mkdir('D:\test\')
f = open(savetarget,'w')
f.write(article)
except Exception as e:
print(" [Failed] - "+ str(e))
else:
time_end=time.time()
print(" [Succeed] - saved to path.") pass
2.图片获取操作
图片获取一般是通过对网页上的<img src="127.0.0.1/png.png">Hello</img>中src上的内容进行下载操作
目前可以使用多种操作方式,例如urlretrieve,不再赘述
Python爬虫框架的更多相关文章
- 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...
- 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...
- Linux 安装python爬虫框架 scrapy
Linux 安装python爬虫框架 scrapy http://scrapy.org/ Scrapy是python最好用的一个爬虫框架.要求: python2.7.x. 1. Ubuntu14.04 ...
- Python爬虫框架Scrapy实例(三)数据存储到MongoDB
Python爬虫框架Scrapy实例(三)数据存储到MongoDB任务目标:爬取豆瓣电影top250,将数据存储到MongoDB中. items.py文件复制代码# -*- coding: utf-8 ...
- Python爬虫框架Scrapy
Scrapy是一个流行的Python爬虫框架, 用途广泛. 使用pip安装scrapy: pip install scrapy scrapy由一下几个主要组件组成: scheduler: 调度器, 决 ...
- 《Python3网络爬虫开发实战》PDF+源代码+《精通Python爬虫框架Scrapy》中英文PDF源代码
下载:https://pan.baidu.com/s/1oejHek3Vmu0ZYvp4w9ZLsw <Python 3网络爬虫开发实战>中文PDF+源代码 下载:https://pan. ...
- Python爬虫框架Scrapy教程(1)—入门
最近实验室的项目中有一个需求是这样的,需要爬取若干个(数目不小)网站发布的文章元数据(标题.时间.正文等).问题是这些网站都很老旧和小众,当然也不可能遵守 Microdata 这类标准.这时候所有网页 ...
- 常见Python爬虫框架你会几个?
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:三名狂客 正文 注意:如果你Python技术学的不够好,可以点击下方链接 ...
- 《精通Python爬虫框架Scrapy》学习资料
<精通Python爬虫框架Scrapy>学习资料 百度网盘:https://pan.baidu.com/s/1ACOYulLLpp9J7Q7src2rVA
- Python爬虫框架Scrapy获得定向打击批量招聘信息
爬虫,就是一个在网上到处或定向抓取数据的程序,当然,这样的说法不够专业,更专业的描写叙述就是.抓取特定站点网页的HTML数据.只是因为一个站点的网页非常多,而我们又不可能事先知道全部网页的URL地址, ...
随机推荐
- Spring boot POST 提交错误 Request header is too large
解决方法 application.yml server: # 单位 KB max-http-header-size: 100000 java.lang.IllegalArgumentException ...
- 从Windows命令行启动MySQL
SERVER: 从Windows命令行启动MySQL 可以从命令行手动启动MySQL服务器.可以在任何版本的Windows中实现. 要想从命令行启动mysqld服务器,你应当启动控制台窗口(或“DOS ...
- Java基础 switch 表达式为字符串
JDK :OpenJDK-11 OS :CentOS 7.6.1810 IDE :Eclipse 2019‑03 typesetting :Markdown code ...
- Flutter和原生交互学习
PlatformChannel功能简介 PlatformChannel分为BasicMessageChannel.MethodChannel以及EventChannel三种.其各自的主要用途如下: B ...
- pytorch 计算图像数据集的均值和标准差
在使用 torchvision.transforms进行数据处理时我们经常进行的操作是: transforms.Normalize((0.485,0.456,0.406), (0.229,0.224, ...
- python web 框架
Web框架(Web framework)是一种开发框架,用来支持动态网站.网络应用和网络服务的开发. wsgiref模块 wsgiref模块就是python基于wsgi协议(Web Server Ga ...
- Spring MVC 为控制器添加通知与处理异常
与Spring AOP一样,Spring MVC也能够给控制器加入通知,它主要涉及4个注解: •@ControllerAdvice,主要作用于类,用以标识全局性的控制器的拦截器,它将应用于对应的控制器 ...
- LeetCode_204. Count Primes
204. Count Primes Easy Count the number of prime numbers less than a non-negative number, n. Example ...
- node不要使用最新版本,使用LTS版本
错误现象 const { Math, Object, Reflect } = primordials; 原因 使用了最新的node版本 解决 使用稳定版本,参考官网说明,目前10.x的版本是稳定版本( ...
- 安装Windows和Ubuntu双系统
发现关注消息 安装Windows和Ubuntu双系统 安装Windows和Ubuntu双系统 0.552016.12.10 15:54:41字数 2101阅读 6644 这几天开始动手做毕设啦 ...