利用爬虫技术能做到哪些很酷很有趣很有用的事情?
谢邀。
我用爬虫爬了我爱白菜网、超值分享汇、发现值得买、惠惠购物、今日聚超值、留住你、买手党、没得比、慢慢买、牛杂网、买个便宜货、什么值得买、天上掉馅饼、一分网、折800值得买、值值值等网站的折扣信息。
这些网站都是提供的一些及时的、性价比较高的商品,很多时候要一个一个网站的看(重度用户),很容易就会错过一些很划算的商品。
于是用Python抓取了这些打折信息,并输出到网站上(
)。
#-*- coding: utf-8 -*-
from Haohuola.Base import p
from bs4 import BeautifulSoup
import PostMessage,json
from se import getGoodsUrl
from qiniuUpload import getImageUrl
from Haohuola.Base import getHtml,getMallCountry,get_title_price
from Haohuola.Base import getTags,handle_content
from Haohuola.Category import getCategory
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1) 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,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,ja;q=0.2,fr;q=0.2,es;q=0.2,ru;q=0.2',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Host':'www.czfxh.com',
}
html=getHtml('http://www.czfxh.com',headers).decode('utf-8')
soup=BeautifulSoup(html)
AUTHOR=u"超值分享汇"
soupid=soup.find(id="main")
items=soupid.find_all("div",{"class":"post"})[0:8]
items.reverse()
for item in items:
try:
link=item.find('div',{'class':'buy_url'}).a['href'].encode('utf-8') #原始购买链接
title=item.h2.get_text().encode('utf-8')
if PostMessage.urlToSQL(link)==1:
tuple_url=getGoodsUrl(link)
links=tuple_url[0]
mobile=tuple_url[2]
if not links:
continue
if PostMessage.transToSQL(tuple_url)==1:
title=item.h2.get_text().encode('utf-8')
alltitle=get_title_price(title)
price=alltitle['price'] #提取出价格来
article_title=alltitle['article_title'] #标题
publish_title=alltitle['publish_title']
content=str(item.find('div',{'class':'content'}).select('.conBox')[0])
publish_content,img_url=handle_content(content)
image_url=getImageUrl(img_url,publish_title)
MallCountry = getMallCountry(links) #获取商城和国内还是海淘(links是转换后的链接)
country = MallCountry["region"] #中国的或者是海淘的
mall = MallCountry["mall"] #商品来自拿个商城
Category = getCategory(publish_title)
category = Category['code']
tags = getTags(Category,mall) #商品标签
res=PostMessage.postMessage(publish_title,publish_content,AUTHOR,links,mall,image_url,price,tags,country,article_title,category,mobile)
p(u'---start---',publish_title,publish_content,AUTHOR,links,mall,image_url,price,tags,country,article_title,category,mobile,u'---end---')
if res==True:
PostMessage.insertIntoOriginal(link)
PostMessage.insertIntoSQL(tuple_url)
else:
PostMessage.insertIntoOriginal(link)
continue
except Exception, e:
print e
continue
抓取这部分难度并不是很大,用requests+beautifulSoup基本上可以抓下全部内容来。
难点主要由三个方面:
1.去重
这些网站有很大部分也是相同的,因此要将重复的去除掉,去除的标准是根据商品链接转换为原始链接(自身都是带返利的,所以须转换后才可以比较)。另外还要家一定的时间限制,即超过一周后同一个商品的链接视为该店铺再次打折被推荐。
2.转换链接
这是比较困难的一部分,商品的返利链接都是加密转换了的,很难直接还原,于是采用了简单粗暴的方法,用 PhantomJS 模拟浏览器打开链接并获取跳转后的原始链接,这一部分原理上也还简单,但是每个商城都有很多例外情况要处理,最后完善下来也要500行以上代码才搞定。
3.自动分类
通过不同分类中关键词出现的频率来得出改商品所属的分类,主要是利用一些统计知识,并在后期通过纠正使其越来越准确。
现在网站自己用着还不错,后期会加入推送、关键词订阅等功能,并且加上个人筛选功能(来源网站、性别、分类等)。
最后贴个地址,也算是做个小广告: