爬取大众点评网的某城市美食店铺数据

前言

某旅游城市在今年的十一期间再次火爆了一把,城市的各种美食确实让人垂涎欲滴。因此,个人萌生了爬取该城市美食店铺信息的想法。

一、确定爬取的url

1.首先用浏览器打开大众点评网站www.dianping.com,然后点击城市链接 ,再点击美食链接进入城市美食页面。

地址为:http://www.dianping.com/changsha/ch10/p0

2.改变页码,发现只有最后的px会发生变化。因此,只需要简单构建循环即可构造url地址。

二、开始抓取


1.直接抓取

查看网页源代码,发现可以搜索到网页中存在的信息,因此基本可以确定是静态网页。


仅仅添加useragent直接进行抓取后,发现出现了302状态码进行了跳转。这种情况下,应该是需要增加请求头信息。

2.构造请求头

1.查看网页请求头如下图!


几次刷新页面后发现,改变的数据仅仅是cookie,其它请求头信息均为固定信息。每次cookie均发生了改变,但是并没有进行两次加载,说明cookie信息应该是本地生成的。cookie信息中有两项信息会发生改变,


其中,_lxsdk_s每次的改变很有规律,为最后两位数加20或者21(具体是20还是21自己可以刷新几次看一下)。但是另一项就比较复杂,看起来像是时间戳,但是尝试后发现并不是。既然是本地生成的,那么查看js应该可以看到生成方式,个人尝试了一下,无奈js能力有限。

但是,既然是本地生成的,那么我们可以进行分析,在浏览器和页面内容均没有发生改变的情况下,改变的只有加载时间,我们可以大胆猜测这个数据还是和时间有关系。而且response headers中还有一项Set-Cookie,里面的数据仅有时间在发生改变,基本可以确认Hm_lpvt的改变是由时间引起的。


```python

17-Nov-2022 07:22:07 GMT 1605596557

17-Nov-2022 07:31:29 GMT 1605597742

17-Nov-2022 07:31:59 GMT 1605598305

```

如图,查看几次请求信息,最后观察到每一次的Hm_lpvt的改变量为前次请求的时间间隔,其实也就是每次请求的Hm_lpvt信息,实际上是与上一次请求时间以及第一次请求时间相关的。

那么我们可以就此构造cookie。考虑到万一某次请求出现问题方便再次构造cookie,因此本人将构造cookie需要的三项数据写入txt文件,每次进行读取和写入操作。

```python

`def get_cookie():

    new = """fspop=test; _lxsdk_cuid=175a63b9732c8-045b6a35f56618-230346d-1fa400-175a63b9733c8; _lxsdk=175a6

    3b9732c8-045b6a35f56618-230346d-1fa400-175a63b9733c8; _hc.v=500ca2b8-99ea-2512-79b9-579fd5ee6aab.1604811726; s_View

    Type=10; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; cy=344; cye=changsha; _dp.ac.v=136a299d-309b-401a-93d4-

    15565e9b3ec9; ua=dpuser_8849637005; ctu=6785bc81e314ca567cbe3eeabeca236ead9ce92b79a054a5ce52c4d63f36ce8d; Hm_lvt_602b80cf8079ae6591966cc70a3940e7=1604811726,1604835093,1604897708; _lxsdk_s=175ab5b8dc6-68-5d-822%7C%7C{}; Hm_lpvt_602b80cf8079ae6591966cc70a3940e7={}

    """

    with open("cookie.txt", 'r') as f:

        for line in f.readlines():

            time_cookie = json.loads(line)

  #将时间转换成字符串

    timearray1 = time.strptime(time_cookie[1]['time'], "%Y-%m-%d %H:%M:%S")

    timearray0 = time.strptime(time_cookie[0]['time'], "%Y-%m-%d %H:%M:%S")

  #求前两次的时间差

    timedelta = int(time.mktime(timearray1)) - int(time.mktime(timearray0))

  #构造新的cookie需要的数据

    new_cookie = time_cookie[1]['cookie'] + timedelta

    timearray = time.localtime(int(time.time()))

    new_time = time.strftime("%Y-%m-%d %H:%M:%S", timearray)

    new_num = time_cookie[1]['num'] + 20

  #将新的cookie存入文件,并删除第一项cookie

    time_cookie.append({'time':new_time, 'cookie':new_cookie,'num' : new_num})

    time_cookie.pop(0)

    cookie_json = json.dumps(time_cookie)

    with open("cookie.txt", 'w', ) as f:

        f.write(cookie_json)

    return new.format(str(new_num), str(new_cookie))

cookie =get_cookie()

```

构造cookie后再次进行请求,果然,请求成功。

3.抓取信息

为了方便分析页面内容,因此将网页保存在了本地。在此仅进行了店铺名称,店铺得分,店铺评论数和人均消费信息的抓取。使用了pyquery和re模块进行网页解析。

```python

with open('dianping.html', 'r', encoding='utf-8') as f:

    b = ''

    for line in f.readlines():

        b += line

doc = pq(b)

shop_items = doc('#shop-all-list')

shoplist =shop_items('li').items()

shops = []

for shop in shoplist:

    shop_dict = {}

    shop_name = re.search("

(.*?)

", str(shop), re.S).group(1)

    shop_star = re.search(r'

(.*?)
', str(shop), re.S).group(1)

    comments = re.search(r'"shop_iwant_review_click.*?(.*?)', str(shop), re.S).group(1)

    consume = re.search(r'class="mean-price".*?(.*?)', str(shop), re.S).group(1)

    shop_dict['shop_name'] = shop_name

    shop_dict['star'] = shop_star

    shop_dict['comments'] = comments

    shop_dict['consume'] = consume

    shops.append(shop_dict)

pprint.pprint(shops)

```

抓取的结果如图所示:


发现评论数和人均消费的数字,除了‘1’以外均无法正常显示。我们再次查看网页元素。


4.信息解密

如上图所示,网页部分内容进行了加密,无法正常爬取。可以看到右上角位置有css的指示,打开此链接,如下图


其中有很多个字体文件,但是每个字体文件连接后面均说明了文件内容,我们需要的就是shopNum(店铺数字)字体文件内容。

点击此链接进行下载,并使用fontTools进行转换后查看。

```python

from fontTools.ttLib import TTFont

font = TTFont(r'C:\Users\zhaohengcai\Downloads\fb3304fa.woff')

font.saveXML('local_font.xml')

```

查看内容如图


对照店铺源代码与网页显示内容,最后可以发现与上图的蓝色框内的数据对应。但是3-11对应的网页显示内容为3-9和0,我们需要自己进行转换。

```python

passage = """

   

   

   

   

   

   

   

   

   

    """

keylist = re.findall('', passage)

num_dict = {}

for item in keylist:

    if int(item[0]) != 11:

        num_dict[r'\u' + item[1]] = int(item[0]) - 1

    else:

        num_dict[r'\u' + item[1]] = 0

print(num_dict)

返回去将解析网页内容的代码进行适当修改,使用re进行替换,

num_key = {'\ue486': '2', '\ueb23': '3', '\uf298': '4', '\uf240': '5', '\uf001': '6', '\ue997': '7', '\uf59a': '8', '\uee87': '9', '\uf876': '0'}

with open('dianping.html', 'r', encoding='utf-8') as f:

    b = ''

    for line in f.readlines():

        b += line

doc = pq(b)

shop_items = doc('#shop-all-list')

shoplist =shop_items('li').items()

shops = []

for shop in shoplist:

    shop_dict = {}

    shop_name = re.search("

(.*?)

", str(shop), re.S).group(1)

    shop_star = re.search(r'

(.*?)
', str(shop), re.S).group(1)

    comments = re.search(r'"shop_iwant_review_click.*?(.*?)', str(shop), re.S).group(1)

    #将(.*?)的内容进行替换

    comments_key = re.findall('(.*?)', str(comments), re.S)

    for item in comments_key:

        pattern  = re.compile('{}'.format(item))

        comments = re.sub(pattern, num_key[item], comments)

    consume = re.search(r'class="mean-price".*?(.*?)', str(shop), re.S).group(1)

    #将(.*?)的内容进行替换

    consume_key = re.findall('(.*?)', str(consume), re.S)

    for item in consume_key:

        pattern = re.compile('{}'.format(item))

        consume= re.sub(pattern, num_key[item], consume)

    shop_dict['shop_name'] = shop_name

    shop_dict['star'] = shop_star

    shop_dict['comments'] = comments

    shop_dict['consume'] = consume

    shops.append(shop_dict)

pprint.pprint(shops)

```

运行结果如下:


三、将数据保存到数据库

这样我们的工作基本上就完成了,然后我们可以将数据存入数据库:

```python

myclient = pymongo.MongoClient('localhost', 27017)

dianping_db = myclient['dianping']

dianping_col = dianping_db['dianping_food']

dianping_col.insert_one(shop_dict)

```

之后,我们将代码进行整合。

```python

import json

import pprint

import random

import re

import time

import pymongo

import requests

from pyquery import PyQuery as pq

user_agents = [

    'Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',

    'Mozilla/5.0(Windows;U;MSIE 9.0;Windows NT 9.0;en-US)',

    'Mozilla/5.0(Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0Safari/537.2',

    'Mozilla/5.0(X11; Ubuntu;Linux i686;rv:15.0) Gecko/20100101 Firefox/15.0.1']

headers = {

    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',

    'User-Agent': random.choice(user_agents),

    'Connection': 'keep - alive',

    'Host': 'www.dianping.com',

    'Upgrade-Insecure-Requests': '1',

}

myclient = pymongo.MongoClient('localhost', 27017)

dianping_db = myclient['dianping']

dianping_col = dianping_db['dianping_food']

time_cookie = []

time_cookie.append({"time": "2020-11-17 08:07:36", "cookie": 1605571660, "num": 40})

time_cookie.append({"time": "2020-11-17 08:09:37", "cookie": 1605571671, "num": 60})

timestamp = int(time.time())

timearray = time.localtime(timestamp)

def get_cookie():

    new = """_lxsdk_cuid=175a63b9732c8-045b6a35f56618-230346d-1fa400-175a63b9733c8; _lxsdk=175a63b9732c8-045b6a35f56618

    -230346d-1fa400-175a63b9733c8; _hc.v=500ca2b8-99ea-2512-79b9-579fd5ee6aab.1604811726; s_ViewType=10; cy=344; cye=ch

    angsha; _dp.ac.v=136a299d-309b-401a-93d4-15565e9b3ec9; ua=dpuser_8849637005; ctu=6785bc81e314ca567cbe3eeabeca236ead

    9ce92b79a054a5ce52c4d63f36ce8d; fspop=test; Hm_lvt_602b80cf8079ae6591966cc70a3940e7=1604986265,1605266096,16055297

    94,1605571653; _lxsdk_s=175d38722cb-a29-e6e-f2b%7C%7C{}; Hm_lpvt_602b80cf8079ae6591966cc70a3940e7={}

    """

    with open("cookie.txt", 'r') as f:

        for line in f.readlines():

            time_cookie = json.loads(line)

    timearray1 = time.strptime(time_cookie[1]['time'], "%Y-%m-%d %H:%M:%S")

    timearray0 = time.strptime(time_cookie[0]['time'], "%Y-%m-%d %H:%M:%S")

    timedelta = int(time.mktime(timearray1)) - int(time.mktime(timearray0))

    new_cookie = time_cookie[1]['cookie'] + timedelta

    timearray = time.localtime(int(time.time()))

    new_time = time.strftime("%Y-%m-%d %H:%M:%S", timearray)

    new_num = time_cookie[1]['num'] + 20

    time_cookie.append({'time': new_time, 'cookie': new_cookie, 'num': new_num})

    time_cookie.pop(0)

    cookie_json = json.dumps(time_cookie)

    with open("cookie.txt", 'w', ) as f:

        f.write(cookie_json)

    return new.format(str(new_num), str(new_cookie))

def get_page(url):

    a = get_cookie()

    new_cookie = {'Cookie': a}

    response = requests.get(url=url, headers=headers, cookies=new_cookie)

    with open('dianping.html', 'w', encoding='utf-8') as f:

        f.write(response.text)

    return response

def parse(response):

    doc = pq(response.text)

    shop_items = doc('#shop-all-list')

    shoplist =shop_items('li').items()

    shops = []

    num_key = {'\ue486': '2', '\ueb23': '3', '\uf298': '4', '\uf240': '5', '\uf001': '6', '\ue997': '7', '\uf59a': '8', '\uee87': '9', '\uf876': '0'}

    for shop in shoplist:

        shop_dict = {}

        shop_name = re.search("

(.*?)

", str(shop), re.S).group(1)

        shop_star = re.search(r'

(.*?)
', str(shop), re.S).group(1)

        comments = re.search(r'"shop_iwant_review_click.*?(.*?)', str(shop), re.S).group(1)

        comments_key = re.findall('(.*?)', str(comments), re.S)

        for item in comments_key:

            pattern = re.compile('{}'.format(item))

            comments = re.sub(pattern, num_key[item], comments)

        consume = re.search(r'class="mean-price".*?(.*?)', str(shop), re.S).group(1)

        consume_key = re.findall('(.*?)', str(consume), re.S)

        for item in consume_key:

            pattern = re.compile('{}'.format(item))

            consume = re.sub(pattern, num_key[item], consume)

        shop_dict['shop_name'] = shop_name

        shop_dict['star'] = shop_star

        shop_dict['comments'] = comments

        shop_dict['consume'] = consume

        dianping_col.insert_one(shop_dict)

        shops.append(shop_dict)

    pprint.pprint(shops)

def main():

    for page_num in range(10):

        print('-------------正在爬取第{}页数据--------------'.format(page_num))

        url = 'http://www.dianping.com/changsha/ch10/p{}'.format(page_num)

        response = get_page(url)

        parse(response)

        time.sleep(3)

if __name__ == '__main__':

    main()

```

四、总结

一、本次爬取的难点主要有两个方面:

1.cookie的构造;

2.店铺信息的解密。

cookie的构造,对擅长js解密的人应该比较简单,不擅长js的话,只能像我一样进行分析。

店铺信息的解密,有很多人都写了,在此不再赘述。

二、关于后续爬取的思考

其实应该讲爬取的内容存入mysql数据库,方便后续爬取评论内容的时候进行关联。使用mongoDB不方便数据的关联。

你可能感兴趣的:(爬取大众点评网的某城市美食店铺数据)