哈哈,要做勤劳的小蜜蜂~
上一篇返利网并没有爬好 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()