爬虫实例 爬取美团评论

爬虫爬取美团评论

导入库是由于库里有咱们须要用的函数,这些函数能帮咱们实现某些功能mysql

import requests
import json
import pymysql

你要提取什么数据?web

假如咱们要提取美团一家娱乐场所的评论sql

连接地址:"https://i.meituan.com/xiuxianyule/api/getCommentList?poiId=184022819&offset=0&pageSize=10&sortType=1&mode=0&starRange=10%2C20%2C30%2C40%2C50&tag=数据库

爬取这些评论
在这里插入图片描述
发送请求,得到响应。
咱们已经有url,能够经过浏览器向服务器发送请求了。但实际是咱们并非经过浏览器向服务器发送请求的,而是经过爬虫。若是服务器识别出来请求时爬虫发出来的,那么咱们就会被屏蔽掉,得到不了任何响应。因此咱们要把咱们写的爬虫包装成浏览器。
那咱们如何在向服务器发送请求的时候,不被识别为爬虫。要想不被识别为爬虫,那就须要先假装成浏览器,这须要在发送请求的时候加上headers参数。json

在这里插入图片描述这里就是咱们要的东西
接下来是代码展现api

import requests
import json
import pymysql
#建立数据库链接
try:
    conn=pymysql.connect(host="localhost",user="root",passwd="123456",db="qu")
except:
    print("数据库链接失败")
#建立游标对象
cur=conn.cursor()
#假装浏览器
headers_dict={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36"
}
def pc_comment():
    url="https://i.meituan.com/xiuxianyule/api/getCommentList?poiId=184022819&offset=0&pageSize=10&sortType=1&mode=0&starRange=10%2C20%2C30%2C40%2C50&tag="
    response=requests.get(url,headers=headers_dict)
    #将json字符串转换成字典
    dict1=json.loads(response.text)
    # print(dict1["data"]["commentTagDTOList"])
    for item in dict1["data"]["commentTagDTOList"]:
        zz=item["count"]
        rq=item["tag"]
        print(rq)
        #声明sql语句
        sql="insert into test(name,talk) value('"+str(zz)+"','"+rq+"')"
        cur.execute(sql)
        conn.commit()
    conn.close()
pc_comment()

由于有些网站不是异步请求,因此在这里咱们不须要写代理浏览器

运行结果:
在这里插入图片描述再到数据库中查看,是否是已经成功导入数据库中了
在这里插入图片描述服务器