起初想用scrapy爬虫框架去实现,以为定制开拓的话用scrapy只能用到里面的一些根本的功能,有一些情形要随着框架的规则走,如果自己写的话可以自己写规则去处理,也有优点爬虫、处理器等,末了还是自己写了一个demo。

首先剖析需求,python做爬虫,dedecms做发布,起初先考虑了发布功能,实现了仿照上岸,或者研究dedecms的数据库设计,直接写到数据库,实际中没有这样去做,开始做仿照上岸的时候,须要改dedecms的代码去掉验证码,不然还要实现验证码识别,这个完备没有必要,由于要发布的是自己的网站,自己也有账户、密码、发布文章权限,然后就改了下dedecms的上岸功能,加了一个上岸接口,剖析了dedecms的发布文章HTTP数据包。
这块搞定了后就开始设计爬虫了,末了设计的觉得和scrapy的一些根本的处理机制很像。

做dedecms的上岸接口如下:

dedecmsjspPython编程应用爬虫合营dedecms全主动采集宣布 GraphQL

后台目录下的config.php 34行找到

/

//考验用户登录状态

$cuserLogin = new userLogin();

if($cuserLogin->getUserID()==-1)

{

header(“location:login.php?gotopage=”.urlencode($dedeNowurl));

exit();

}

/

改为下面

//http://127.0.0.2/dede/index.php?username=admin&password=admin

123456789101112$cuserLogin = new userLogin();if($cuserLogin->getUserID()==-1) {if($_REQUEST['username'] != ''){$res = $cuserLogin->checkUser($_REQUEST['username'], $_REQUEST['password']);if($res==1) $cuserLogin->keepUser();}if($cuserLogin->getUserID()==-1) {header(\公众location:login.php?gotopage=\"大众.urlencode($dedeNowurl));exit();}}

这样只要要求:http://127.0.0.2/dede/index.php?username=admin&password=admin 就可以得到一个sessionid,只要用这个sessionid去发布文章就可以了。

发布文章的HTTP数据包如下:

#http://127.0.0.2/dede/article_add.php

POST /dede/article_add.php HTTP/1.1

Host: 127.0.0.2

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://127.0.0.2/dede/article_add.php?cid=2

Cookie: menuitems=1_1%2C2_1%2C3_1; CNZZDATA1254901833=1497342033-1472891946-%7C1473171059; Hm_lvt_a6454d60bf94f1e40b22b89e9f2986ba=1472892122; ENV_GOBACK_URL=%2Fmd5%2Fcontent_list.php%3Farcrank%3D-1%26cid%3D11; lastCid=11; lastCid__ckMd5=2f82387a2b251324; DedeUserID=1; DedeUserID__ckMd5=74be9ff370c4536f; DedeLoginTime=1473174404; DedeLoginTime__ckMd5=b8edc1b5318a3923; hasshown=1; Hm_lpvt_a6454d60bf94f1e40b22b89e9f2986ba=1473173893; PHPSESSID=m2o3k882tln0ttdi964v5aorn6

Connection: keep-alive

Upgrade-Insecure-Requests: 1

Content-Type: multipart/form-data; boundary=—————————2802133914041

Content-Length: 3639

—————————–2802133914041

Content-Disposition: form-data; name=”channelid”

1

—————————–2802133914041

Content-Disposition: form-data; name=”dopost”

save

—————————–2802133914041

Content-Disposition: form-data; name=”title”

2222222222

—————————–2802133914041

Content-Disposition: form-data; name=”shorttitle”

—————————–2802133914041

Content-Disposition: form-data; name=”redirecturl”

—————————–2802133914041

Content-Disposition: form-data; name=”tags”

—————————–2802133914041

Content-Disposition: form-data; name=”weight”

100

—————————–2802133914041

Content-Disposition: form-data; name=”picname”

—————————–2802133914041

Content-Disposition: form-data; name=”litpic”; filename=””

Content-Type: application/octet-stream

—————————–2802133914041

Content-Disposition: form-data; name=”source”

—————————–2802133914041

Content-Disposition: form-data; name=”writer”

—————————–2802133914041

Content-Disposition: form-data; name=”typeid”

2

—————————–2802133914041

Content-Disposition: form-data; name=”typeid2″

—————————–2802133914041

Content-Disposition: form-data; name=”keywords”

—————————–2802133914041

Content-Disposition: form-data; name=”autokey”

1

—————————–2802133914041

Content-Disposition: form-data; name=”description”

—————————–2802133914041

Content-Disposition: form-data; name=”dede_addonfields”

—————————–2802133914041

Content-Disposition: form-data; name=”remote”

1

—————————–2802133914041

Content-Disposition: form-data; name=”autolitpic”

1

—————————–2802133914041

Content-Disposition: form-data; name=”needwatermark”

1

—————————–2802133914041

Content-Disposition: form-data; name=”sptype”

hand

—————————–2802133914041

Content-Disposition: form-data; name=”spsize”

5

—————————–2802133914041

Content-Disposition: form-data; name=”body”

2222222222

—————————–2802133914041

Content-Disposition: form-data; name=”voteid”

—————————–2802133914041

Content-Disposition: form-data; name=”notpost”

0

—————————–2802133914041

Content-Disposition: form-data; name=”click”

70

—————————–2802133914041

Content-Disposition: form-data; name=”sortup”

0

—————————–2802133914041

Content-Disposition: form-data; name=”color”

—————————–2802133914041

Content-Disposition: form-data; name=”arcrank”

0

—————————–2802133914041

Content-Disposition: form-data; name=”money”

0

—————————–2802133914041

Content-Disposition: form-data; name=”pubdate”

2016-09-06 23:07:52

—————————–2802133914041

Content-Disposition: form-data; name=”ishtml”

1

—————————–2802133914041

Content-Disposition: form-data; name=”filename”

—————————–2802133914041

Content-Disposition: form-data; name=”templet”

—————————–2802133914041

Content-Disposition: form-data; name=”imageField.x”

41

—————————–2802133914041

Content-Disposition: form-data; name=”imageField.y”

6

—————————–2802133914041–

#更新天生html要求

http://127.0.0.2/dede/task_do.php?typeid=2&aid=109&dopost=makeprenext&nextdo=

GET /dede/task_do.php?typeid=2&aid=109&dopost=makeprenext&nextdo= HTTP/1.1

Host: 127.0.0.2

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://127.0.0.2/dede/article_add.php

Cookie: menuitems=1_1%2C2_1%2C3_1; CNZZDATA1254901833=1497342033-1472891946-%7C1473171059; Hm_lvt_a6454d60bf94f1e40b22b89e9f2986ba=1472892122; ENV_GOBACK_URL=%2Fmd5%2Fcontent_list.php%3Farcrank%3D-1%26cid%3D11; lastCid=11; lastCid__ckMd5=2f82387a2b251324; DedeUserID=1; DedeUserID__ckMd5=74be9ff370c4536f; DedeLoginTime=1473174404; DedeLoginTime__ckMd5=b8edc1b5318a3923; hasshown=1; Hm_lpvt_a6454d60bf94f1e40b22b89e9f2986ba=1473173893; PHPSESSID=m2o3k882tln0ttdi964v5aorn6

Connection: keep-alive

Upgrade-Insecure-Requests: 1

通过上面数据包可以剖析到如下结果:

POST http://127.0.0.2/dede/article_add.php

须要配置的参数:

channelid:1 #普通文章提交

dopost:save #提交办法

shorttitle:” #短标题

autokey:1 #自动获取关键词

remote:1 #不指定缩略图,远程自动获取缩略图

autolitpic:1 #提取第一个图片为缩略图

sptype:auto #自动分页

spsize:5 #5k大小自动分页

notpost:1 #禁止评论

sortup:0 #文章排序、默认

arcrank:0 #阅读权限为开放浏览

money: #消费金币0

ishtml:1 #天生html

title:”文章标题” #文章标题

source:”文章来源” #文章来源

writer:”文章作者” #文章作者

typeid:”主栏目ID2″ #主栏目ID

body:”文章内容” #文章内容

click:”文章点击量” #文章点击量

pubdate:”提交韶光” #提交韶光

然后开始仿照dedecms发布文章测试了,python代码如下:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#!/usr/bin/python#coding:utf8import requests,random,time#访问上岸接口保持cookiessid = requests.session()login_url = \"大众http://127.0.0.2/dede/index.php?username=admin&password=admin\公众header = { \公众User-Agent\"大众:\"大众Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0\公众,\"大众Referer\"大众 :\公众http://127.0.0.2\"大众}#上岸接口获取Cookiesloadcookies = sid.get(url = login_url,headers = header)#进入增加文章页面#get_html = sid.get('http://127.0.0.2/dede/article_add.php?channelid=1',headers = header)#print get_html.content#定义固定字段article = {'channelid':1, #普通文章提交'dopost':'save', #提交办法'shorttitle':'', #短标题'autokey':1, #自动获取关键词'remote':1, #不指定缩略图,远程自动获取缩略图'autolitpic':1, #提取第一个图片为缩略图'sptype':'auto', #自动分页'spsize':5, #5k大小自动分页'notpost':1, #禁止评论'sortup':0, #文章排序、默认'arcrank':0, #阅读权限为开放浏览'money': 0,#消费金币0'ishtml':1, #天生html'click':random.randint(10, 300), #随机天生文章点击量'pubdate':time.strftime(\公众%Y-%m-%d %H:%M:%S\"大众, time.localtime()), #s天生当条件交韶光}#定义可变字段article['source'] = \公众文章来源\"大众 #文章来源article['writer'] = \"大众文章作者\"大众 #文章作者article['typeid'] = \"大众2\公众 #主栏目ID#定义提交文章要求URLarticle_request = \"大众http://127.0.0.2/dede/article_add.php\公众\公众\"大众\公众#测试提交数据article['title'] = \"大众测试_文章标题\"大众 #文章标题article['body'] = \"大众测试_文章内容\"大众 #文章内容#提交后会自动重定向 天生html,http返回状态为200则成功!
res = sid.post(url = article_request,data = article, headers = header)print res\"大众\"大众\"大众for i in range(50): article['title'] = str(i) + \"大众_文章标题\"大众 #文章标题 article['body'] = str(i) + \"大众_文章内容\"大众 #文章内容 #print article res = sid.post(url = article_request,data = article, headers = header) print res

其次便是剖析爬虫需求阶段了,如下:

网络采集页面:

http://www.tunvan.com/col.jsp?id=115

http://www.zhongkerd.com/news.html

http://www.qianxx.com/news/field/

http://www.ifenguo.com/news/xingyexinwen/

http://www.ifenguo.com/news/gongsixinwen/

每一个采集页面和要改的规则都不一样,发布文章的栏目可能也有变革,要写多个爬虫,一个爬虫实现不了这个功能,要有爬虫、处理器、配置文件、函数文件(避免重复写代码)、数据库文件。

数据库里面紧张是保存文章url和标题,紧张是判断这篇文章是否是更新的,如果已经采集发布了就不要重复发布了,如果不存在文章便是最新的文章,须要写入数据库并发布文章。
数据库就一个表几个字段就好,采取的sqlite3,数据库文件db.dll建表如下:

123456CREATE TABLE history (id INTEGER PRIMARY KEY ASC AUTOINCREMENT,url VARCHAR( 100 ),title TEXT,DATE DATETIME DEFAULT ( ( datetime( 'now', 'localtime' ) ) ));

架构设计如下:

│ db.dll #sqlite数据库

│ dede.py #测试dede上岸接口

│ function.py #公共函数

│ run.py #爬虫集开始函数

│ settings.py #爬虫配置设置

│ spiders.py #爬虫示例

│ sqlitestudio-2.1.5.exe #sqlite数据库编辑工具

│ __init__.py #前置方法供模块用

dede.py如下:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566#!/usr/bin/python#coding:utf8import requests,random,timeimport lxml#定义域名domain = \公众http://127.0.0.2/\"大众admin_dir = \"大众dede/\"大众houtai = domain + admin_dirusername = \"大众admin\"大众password = \"大众admin\"大众#访问上岸接口保持cookiessid = requests.session()login_url = houtai + \公众index.php?username=\公众 + username + \"大众&password=\"大众 + passwordheader = { \"大众User-Agent\"大众:\"大众Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0\"大众,\公众Referer\公众 : domain}#上岸接口获取Cookiesloadcookies = sid.get(url = login_url,headers = header)#定义固定字段article = {'channelid':1, #普通文章提交'dopost':'save', #提交办法'shorttitle':'', #短标题'autokey':1, #自动获取关键词'remote':1, #不指定缩略图,远程自动获取缩略图'autolitpic':1, #提取第一个图片为缩略图'sptype':'auto', #自动分页'spsize':5, #5k大小自动分页'notpost':1, #禁止评论'sortup':0, #文章排序、默认'arcrank':0, #阅读权限为开放浏览'money': 0,#消费金币0'ishtml':1, #天生html'click':random.randint(10, 300), #随机天生文章点击量'pubdate':time.strftime(\"大众%Y-%m-%d %H:%M:%S\"大众, time.localtime()), #s天生当条件交韶光}#定义可变字段article['source'] = \"大众文章来源\"大众 #文章来源article['writer'] = \"大众文章作者\"大众 #文章作者article['typeid'] = \"大众2\"大众 #主栏目ID#定义提交文章要求URLarticle_request = houtai + \"大众article_add.php\公众\"大众\公众\公众#测试提交数据article['title'] = \"大众11测试_文章标题\公众 #文章标题article['body'] = \"大众11测试_文章内容\"大众 #文章内容#提交后会自动重定向 天生html,http返回状态为200则成功!
res = sid.post(url = article_request,data = article, headers = header)print res\公众\"大众\"大众\"大众\"大众\"大众for i in range(50): article['title'] = str(i) + \"大众_文章标题\"大众 #文章标题 article['body'] = str(i) + \公众_文章内容\公众 #文章内容 #print article res = sid.post(url = article_request,data = article, headers = header) print res\公众\"大众\"大众

function.py如下:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# coding:utf-8from settings import #检讨数据库中是否存在文章,0为不存在,1为存在def res_check(article): exec_select = \"大众SELECT count() FROM history WHERE url = '%s' AND title = '%s' \公众 res_check = cur.execute(exec_select % (article[0],article[1])) for res in res_check: result = res[0] return result#写入数据库操作def res_insert(article): exec_insert = \公众INSERT INTO history (url,title) VALUES ('%s','%s')\公众 cur.execute(exec_insert % (article[0],article[1])) conn.commit()#仿照上岸发布文章def send_article(title,body,typeid = \"大众2\公众): article['title'] = title #文章标题 article['body'] = body #文章内容 article['typeid'] = \公众2\公众 #print article #提交后会自动重定向 天生html,http返回状态为200则成功!
res = sid.post(url = article_request,data = article, headers = header) #print res if res.status_code == 200 : #print u\"大众send mail!\公众 send_mail(title = title,body = body) print u\"大众success article send!\公众 else: #发布文章失落败处理 pass#发邮件关照send_mail(收件,标题,内容)def send_mail(title,body): shoujian = \"大众admin@0535code.com\"大众 # 设置做事器,用户名、密码以及邮箱的后缀 mail_user = \"大众610358898\"大众 mail_pass=\公众你的邮箱密码\"大众 mail_postfix=\"大众qq.com\公众 me=mail_user+\"大众<\"大众+mail_user+\"大众@\公众+mail_postfix+\"大众>\"大众 msg = MIMEText(body, 'html', 'utf-8') msg['Subject'] = title #msg['to'] = shoujian try: mail = smtplib.SMTP() mail.connect(\公众smtp.qq.com\"大众)#配置SMTP做事器 mail.login(mail_user,mail_pass) mail.sendmail(me,shoujian, msg.as_string()) mail.close() print u\"大众send mail success!\"大众 except Exception, e: print str(e) print u\"大众send mail exit!\"大众

run.py如下:

1234# -- coding: utf-8 --import spiders #开始第一个爬虫 spiders.start()

settings.py如下:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# coding:utf-8import re,sys,os,requests,lxml,string,time,random,loggingfrom bs4 import BeautifulSoupfrom lxml import etreeimport smtplibfrom email.mime.text import MIMETextimport sqlite3import HTMLParser#刷新系统reload(sys)sys.setdefaultencoding( \"大众utf-8\"大众 )#定义当前韶光#now = time.strftime( '%Y-%m-%d %X',time.localtime())#设置头信息headers={ \公众User-Agent\"大众:\"大众Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36\公众,\公众Accept\"大众:\"大众/\公众,\"大众Accept-Language\"大众:\"大众zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\"大众,\公众Accept-Encoding\"大众:\"大众gzip, deflate\"大众,\"大众Content-Type\"大众:\"大众application/x-www-form-urlencoded; charset=UTF-8\公众,\"大众Connection\公众:\"大众keep-alive\"大众,\"大众X-Requested-With\公众:\"大众XMLHttpRequest\"大众,}domain = u\"大众<a href='http://010bjsoft.com'>北京软件外包</a>\"大众.decode(\"大众string_escape\"大众) #要更换的超链接html_parser = HTMLParser.HTMLParser() #天生转义器########################################################dede参数配置#定义域名domain = \"大众http://127.0.0.2/\"大众admin_dir = \"大众dede/\公众houtai = domain + admin_dirusername = \公众admin\"大众password = \"大众admin\"大众#访问上岸接口保持cookiessid = requests.session()login_url = houtai + \"大众index.php?username=\公众 + username + \"大众&password=\公众 + passwordheader = { \"大众User-Agent\"大众:\"大众Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0\"大众,\公众Referer\"大众 : domain}#上岸接口获取Cookiesloadcookies = sid.get(url = login_url,headers = header)#定义固定字段article = {'channelid':1, #普通文章提交'dopost':'save', #提交办法'shorttitle':'', #短标题'autokey':1, #自动获取关键词'remote':1, #不指定缩略图,远程自动获取缩略图'autolitpic':1, #提取第一个图片为缩略图'sptype':'auto', #自动分页'spsize':5, #5k大小自动分页'notpost':1, #禁止评论'sortup':0, #文章排序、默认'arcrank':0, #阅读权限为开放浏览'money': 0,#消费金币0'ishtml':1, #天生html'click':random.randint(10, 300), #随机天生文章点击量'pubdate':time.strftime(\"大众%Y-%m-%d %H:%M:%S\"大众, time.localtime()), #s天生当条件交韶光}#定义可变字段article['source'] = \"大众文章来源\公众 #文章来源article['writer'] = \公众文章作者\"大众 #文章作者#定义提交文章要求URLarticle_request = houtai + \"大众article_add.php\公众########################################################数据库配置#建立数据库连接conn = sqlite3.connect(\公众db.dll\"大众)#创建游标cur = conn.cursor()

spiders.py如下:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# coding:utf-8from settings import from function import #获取内容, 文章url,文章内容xpath表达式def get_content( url = \公众http://www.zhongkerd.com/news/content-1389.html\公众 , xpath_rule = \"大众//html/body/div[3]/div/div[2]/div/div[2]/div/div[1]/div/div/dl/dd\"大众 ): html = requests.get(url,headers = headers).content tree = etree.HTML(html) res = tree .xpath(xpath_rule)[0] res_content = etree.tostring(res) #转为字符串 res_content = html_parser.unescape(res_content) #转为html编码 输出 res_content = res_content.replace('\t','').replace('\n','') #去除空格 .replace(' ',''),换行符,制表符 return res_content#获取结果,url列表def get_article_list(url = \"大众http://www.zhongkerd.com/news.html\"大众 ): body_html = requests.get(url,headers = headers).content #print body_html soup = BeautifulSoup(body_html,'lxml') page_div = soup.find_all(name = \公众a\"大众,href = re.compile(\"大众content\"大众),class_=\"大众w-bloglist-entry-link\"大众) #print page_div list_url = [] for a in page_div: #print a #print a.get('href') #print a.string list_url.append((a.get('href'),a.string)) #print get_content(a.get('href')) else: #print list_url return list_url#处理采集页面def res_content(url): content = get_content(url) #print content info = re.findall(r'<dd>(.?)</dd>',content,re.S)[0] #去掉dd标签 re_zhushi = re.compile(r'<!--[^>]-->') #HTML注释 re_href = re.compile(r'<\sa[^>]>[^<](.?)<\s/\sa\s>') #去出超链接,更换 re_js = re.compile(r'<\sscript[^>]>[^<](.?)<\s/\sscript\s>') #去出 javascript re_copyright = re.compile(r'<p\salign=\\"大众left\\公众>(.?)</p>') #去出 版权信息 #r'<p\salign=\\"大众left\\"大众>' 把稳处理换行要 info = re_zhushi.sub('',info,re.S) info = re_href.sub(domain,info,re.S) #print content #exit() info = re_copyright.sub(u\公众\公众,info,re.S) info = info.replace(u'\xa0', u' ') #防止gbk转btf输出错误 #print info return info#处理结果def caiji_result(): article_list = get_article_list() #print article_list #判断是否数据库中是否有,是否写入数据库 for article in article_list: #print res_check(article) #判断是否须要写入 if not res_check(article): #print \"大众no\公众 #u\"大众不存在须要写入\"大众 res_insert(article) #写入后须要发布文章 body = res_content(article[0]) send_article(title = article[1],body = body) else: #print \公众yes\"大众 #u\"大众已经存在不须要写入\"大众 pass#爬虫调用函数def start(): caiji_result()

__init__.py用于发布模块时用。

写完了、是不是创造和scrapy根本功能有点像呢。


作者:网痴