python爬取返利网(完善)

哈哈,要做勤劳的小蜜蜂~

上一篇返利网并没有爬好 http://blog.csdn.net/tt_258/article/details/50300643

在高人的指点下,我又回来了,下面是改后的代码

</pre><pre name="code" class="python">
#coding=utf-8
import urllib2
from bs4 import BeautifulSoup
import time
class FLW():
    def __init__(self):
        self.user_agent= 'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)'
        self.headers = {'User_Agent' :self.user_agent}
    def getUrl(self,pageIndex1,pageIndex2):
        url='http://zhide.fanli.com/index/ajaxGetItem?cat_id=0&tag=&page='+str(pageIndex1)+'-'+str(pageIndex2)+'&area=0&tag_id=0&shop_id=0'
        return url
    def getHtml(self,url):
        try:
            request=urllib2.Request(url,headers=self.headers)
            response=urllib2.urlopen(request)
            html=response.read()
            return html
        except urllib2.URLError,e:
            if hasattr(e,'reason'):
                print u'链接失败',e.reason
                return None
    def getStr(self):
        fd=open('flw.txt','a+')
        fd.write('商品名称'+'|'+'分类'+'|'+'推荐人'+'|'+'商品简介'+'|'+'好评数'+'|'+'差评数'+'\n')
        for x in range(1,51):
            for y in range(2,11):
                url=self.getUrl(x,y)
                html=self.getHtml(url)
                soup=BeautifulSoup(html)
                #主要改变在以下部分,将筛选方法改了
                divs=soup.find_all('div',class_='zdm-list-item J-item-wrap item-no-expired')   #找到一个商品的全部代码
                for div in divs:      #在找到的所有代码中,找所需信息,之所以get_text()是因为不能直接写入文档,而且需要去掉多余代码
                    name=div.find('a',{'data-channel':'4'}).get_text(strip=True)  #找商品名称,因为用'class_'有的商品获取不到,所以用了data-channel=4,但                                                                                    4貌似还不能直接用data-channel=4,所以用了字典。
                    fenle=div.find('a', class_="nine").get_text(strip=True)  #找分类
                    person=div.find('div',class_='item-user').get_text(strip=True)  #推荐人
                    pinglun=div.find('div', class_='item-content-inner J-item-content-inner').get_text(strip=True)  #简介
                    yes=div.find('a',class_='l item-vote-yes J-item-vote-yes').string   #好评数
                    no=div.find('a',class_='l item-vote-no J-item-vote-no').string   #差评数
                    fd.write(name+'|'+fenle+'|'+person+'|'+pinglun+'|'+yes+'|'+no+'\n')
            time.sleep(1)  #另,睡眠函数要在for循环里,不然没用处!
        fd.close()
  
spider=FLW()
spider.getStr()


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值