拖了好久的代码

1.首先进入页面确定自己要抓取的数据(我们要抓取的是左侧分类栏-----包括美食、火锅)
先爬取第一级分类(美食、婚纱摄影、电影),之后根据第一级链接爬取第二层(火锅)。要注意第二级的pid是第一级的classid,这样才能区分出第二级分类哪些是属于第一级的。
2.上一步我们分别把链接存入Redis,名称存入了Mongodb,这一步我们要从Redis取链接,取第二级的链接。因为我们要获取店铺的信息(所以取第二级链接就够),我们首先分析取得第一页的内容,然后找到他下一页的代码(取得下一页代码就获取整个分类的店铺)
3.获取店铺信息(根据取得的店铺链接获取对应的店铺信息)
因为我们发现http协议头和cookie我们几乎每次都用到了,所以我们将它们封装成了一个方法,以便用的时候调用。
至此,大众点评就算结束了,只不过还没取评论信息,会慢慢上。

1.py

# -*- coding: utf-8 -*-
import re
from urllib.request import urlopen
from urllib.request import Request
from bs4 import BeautifulSoup
from lxml import etree

from pymongo import MongoClient
client = MongoClient('localhost',27017)
db=client.dianping
collection=db.classification	#类别表

import redis
r = redis.Redis(host='127.0.0.1',port=6379,db=0)

ii=0

def secClassFind(selector,classid):
	global ii
	ii += 1
	secItems = selector.xpath('//div[@class="sec-items"]/a')
	for secItem in secItems:
		url = secItem.get('href')
		title = secItem.text
		classid = collection.insert({'classname':title,'pid':classid})
		classurl = '%s,%s,%i,%s'%(classid,url,ii,title)
		r.lpush('classurl',classurl)

def findRootNode(url):
	headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
	req_timeout = 5
	req = Request(url=url,headers=headers)
	f = urlopen(req,None,req_timeout)
	s=f.read()
	s=s.decode("utf-8")
	# beautiful 提取数据
	soup=BeautifulSoup(s,'html.parser')
	links=soup.find_all(name='li',class_="first-item")
	for link in links:
		selector = etree.HTML(str(link))
		'''
		indexTitleUrls = selector.xpath('//a[@class="index-title"]/@href')
		#获取一级类别url和title
		for titleurl in indexTitleUrls:
			print(titleurl)
		'''
		indexTitles = selector.xpath('//a[@class="index-title"]/text()')
		for title in indexTitles:
			print(title)
			classid = collection.insert({'classname':title,'pid':None})
			#第二级别url
			secClassFind(selector,classid)
			#print(rs)
			print('-------------')

		print('----------------------------------------------')

findRootNode('http://www.dianping.com/')

  2.py

# -*- coding: utf-8 -*-
import re
from urllib.request import urlopen
from urllib.request import Request
from slaver3_list import getCurPageList
from bs4 import BeautifulSoup
from lxml import etree

from pymongo import MongoClient
client = MongoClient('localhost',27017)
db=client.dianping

import redis
r = redis.Redis(host='127.0.0.1',port=6379,db=0)

'''
1.从classurl中取得一个链接
2.根据此链接获得一个列表页面
3.分析获得页面上的店铺链接
4.获得下一页链接
5.继续爬取下一页信息,继续解析获得链接(重复2~5)
    直到没有下一页为止
'''
#1.从redis中获取一个链接
#classurls = bytes.decode(r.lindex('classurl',0))
shopflag = int(r.get('shopflag'))

if shopflag==0:
    collection=db.shops0    #类别表
    collection.remove({})
    r.set(')
else:
    collection=db.shops1    #类别表
    collection.remove({})
    r.set(')

r.delete('shopurl')

list = r.lrange('classurl',0,-1)
for item in list:
    classurl = bytes.decode(item)        #二进制转字符串
    arr = classurl.split(',')
    #print(arr[0])        #classid
    #print(arr[1])        #classurl
    getCurPageList(arr[0],arr[1],shopflag)
    break

'''
print(classurls)
arr = classurls.split(',')

if int(arr[2])==16:
    #调用
    getCurPageList(arr[0],arr[1])
'''

3.py

# -*- coding: utf-8 -*-
import re
#from urllib.request import urlopen
#from urllib.request import Request
from common import httpSpider
from bs4 import BeautifulSoup
from lxml import etree
from bson.objectid import ObjectId
from slaver4_shopinfo import getShopInfo

from pymongo import MongoClient
client = MongoClient('localhost',27017)
db=client.dianping
collection=None

import redis
r = redis.Redis(host='127.0.0.1',port=6379,db=0)

ii=0

#id,店名,类别id
def insertShop(classid,shopList):
    global collection
    for div in shopList:
        #print(div.get("href"))
        #print(div.get('title'))
        url = div.get("href")
        shopid = collection.insert({'_id':url,'shopname':div.get('title'),'classid':ObjectId(classid)})
        # shopurl = '%s,%s,%s'%(classid,shopid,url)
        # r.lpush('shopurl',shopurl)
        getShopInfo(shopid,url)

def getCurPageList(classid,url,shopflag):
    global ii
    ii += 1
    html = httpSpider(url)
    #print(html)

    selector = etree.HTML(html)

    global collection
    if shopflag==0:
            collection=db.shops0    #店铺表
    else:
        collection=db.shops1

    divTits = selector.xpath('//div[@class="tit"]/a[@title]')
    insertShop(classid,divTits)
    '''
    for div in divTits:
        print(div.get("href"))
        print(div.get('title'))
    '''
    print('----------%i---------------'%(ii))
    #-----下一页--------------------------
    '''
    nextPage = selector.xpath('//a[@class="next"]/@href')
    if len(nextPage)>0:
        newUrl = nextPage[0]
        #print(nextPage[0])
        getCurPageList(newUrl)
    '''

4.py

# -*- coding: utf-8 -*-
import re
#from urllib.request import urlopen
#from urllib.request import Request
from common import httpSpider
from bs4 import BeautifulSoup
from lxml import etree
from bson.objectid import ObjectId

from pymongo import MongoClient
client = MongoClient('localhost',27017)
db=client.dianping
collection=db.shops    #店铺表

import redis
r = redis.Redis(host='127.0.0.1',port=6379,db=0)

def getShopInfo(shopid,shopurl):
    html = httpSpider(shopurl)
    selector = etree.HTML(html)
    briefInfo = selector.xpath('//div[@class="brief-info"]//span[@class="item"]')
    for item in briefInfo:
        print(item.text)

common.py

# -*- coding: utf-8 -*-
import urllib.request
from urllib.request import urlopen
from urllib.request import Request
import http.cookiejar

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

head = {
    'Connection': 'Keep-Alive',
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
}

def makeMyOpener(head):
    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    header = []
    for key, value in head.items():
        elem = (key, value)
        header.append(elem)
    opener.addheaders = header
    return opener
def httpSpider(url):
    oper = makeMyOpener(head)
    req_timeout = 5
    uop = oper.open(url, timeout = req_timeout)
    data = uop.read()
    html = data.decode()
    return html

def dynamicSpider(url):
    headers = {
        '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',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4',
        'Connection': 'keep-alive'
    }
    cap = DesiredCapabilities.PHANTOMJS.copy()    #使用copy()防止修改原代码定义dict
    for key, value in headers.items():
        cap['phantomjs.page.customHeaders.{}'.format(key)] = value
    cap["phantomjs.page.settings.loadImages"] = False
    driver = webdriver.PhantomJS(desired_capabilities=cap,executable_path='D:/phantoms/phantomjs-2.1.1-windows/bin/phantomjs.exe')
    driver.get(url)
    html = driver.page_source
    driver.quit()
    return html

python爬取大众点评的更多相关文章

  1. python爬取大众点评并写入mongodb数据库和redis数据库

    抓取大众点评首页左侧信息,如图: 我们要实现把中文名字都存到mongodb,而每个链接存入redis数据库. 因为将数据存到mongodb时每一个信息都会有一个对应的id,那样就方便我们存入redis ...

  2. Python 爬取大众点评 50 页数据,最好吃的成都火锅竟是它!

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 胡萝卜酱 PS:如有需要Python学习资料的小伙伴可以加点击下方链 ...

  3. 用Python爬取大众点评数据,推荐火锅店里最受欢迎的食品

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:有趣的Python PS:如有需要Python学习资料的小伙伴可以加点 ...

  4. python爬虫实战---爬取大众点评评论

    python爬虫实战—爬取大众点评评论(加密字体) 1.首先打开一个店铺找到评论 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经 ...

  5. python爬虫爬取大众点评并导入redis

    直接上代码,导入redis的中文编码没有解决,日后解决了会第一时间上代码!新手上路,多多包涵! # -*- coding: utf-8 -*- import re import requests fr ...

  6. Python爬虫丨大众点评数据爬虫教程(1)

    大众点评数据获取 --- 基础版本 大众点评是一款非常受普罗大众喜爱的一个第三方的美食相关的点评网站. 因此,该网站的数据也就非常有价值.优惠,评价数量,好评度等数据也就非常受数据公司的欢迎. 今天就 ...

  7. Python 爬取所有51VOA网站的Learn a words文本及mp3音频

    Python 爬取所有51VOA网站的Learn a words文本及mp3音频 #!/usr/bin/env python # -*- coding: utf-8 -*- #Python 爬取所有5 ...

  8. python爬取网站数据

    开学前接了一个任务,内容是从网上爬取特定属性的数据.正好之前学了python,练练手. 编码问题 因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这个机会算是彻底搞清楚了. 问题要从文字的编码讲 ...

  9. python爬取某个网页的图片-如百度贴吧

    python爬取某个网页的图片-如百度贴吧 作者:vpoet mail:vpoet_sir@163.com 注:随意copy,不用告诉我 #coding:utf-8 import urllib imp ...

随机推荐

  1. Django框架的安装

    下载Django框架 创建一个django项目 在E盘Mysite文件夹下创建了一个django项目叫mysite 当前文件夹下会产生一个mysite的文件夹,目录结构如下: manage.py -- ...

  2. 工厂模式(Factory Method)

    1.工厂方法模式(Factory Method) 工厂方法模式分为三种: 1-1.普通工厂模式,就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建. 举例如下:(我们举一个发送邮件和短信的例子 ...

  3. 数据库索引------Btree索引的使用限制

    1.如果不是按照索引最左列开始查找,则无法使用索引. 比如说id+name   那么是name+id 的话  ,这个索引则无法使用. 2.使用索引时不能跳过索引中的列.   如果是id+name+ag ...

  4. WeChat 隐私政策

    隐私政策 本应用尊重并保护所有使用服务用户的个人隐私权.为了给您提供更准确.更有个性化的服务,本应用会按照本隐私权政策的规定使用和披露您的个人信息.但本应用将以高度的勤勉.审慎义务对待这些信息.除本隐 ...

  5. python通过webservice接口实现配置下发

    项目上要开发一个小工具,通过webservice接口实现配置下发,考虑到python的第三方库对soap的良好支持,果断决定用python来完成这一使命. Python的支持webservice的第三 ...

  6. 独家探寻阿里安全潘多拉实验室,完美越狱苹果iOS11.2.1

    知道如何从攻击的视角去发现漏洞,才能建立更安全的体系,促进了整个生态的良性发展.以阿里安全潘多拉实验室为例,在对移动系统安全研究的过程中,把研究过程中发现的问题上报给厂商,促进系统安全性的提升. 小编 ...

  7. 【NOI2005】维护数列

    https://daniu.luogu.org/problem/show?pid=2042 一道伸展树维护数列的很悲伤的题目,共要维护两个标记和两个数列信息,为了维护MAX-SUM还要维护从左端开始的 ...

  8. java 之 命令模式(大话设计模式)

    命令模式,笔者一直以为当我们开发的过程中基本上很难用到,直到维护阶段或者重构阶段,我们会发现有些撤销命令和追加命令比较频繁时,自然而然就用到命令模式. 先看下类图 大话设计模式-类图 简单说下类图,最 ...

  9. Chromium与CEF的多进程模型及相关參数

    CEF基于Chromium,也是多进程模型.关于进程模型.參考这里:https://www.chromium.org/developers/design-documents/process-model ...

  10. 两个linux之间拷贝文件及文件夹

    Linux为我们提供了两个用于文件copy的命令.一个是cp,一个是scp,可是他们略有不同,cp 主要是用于在同一台电脑上,在不同的文件夹之间来回copy文件 scp 主要是在不同的Linux系统之 ...