首页 > 其他分享 >美团民宿数据爬取

美团民宿数据爬取

时间:2022-11-01 23:22:42浏览次数:33  
标签:__ 美团 民宿 爬取 pymysql import self

1.美团民宿信息获取

# coding:utf8
import requests
import random
from lxml import etree
import time
# 提供ua信息的的包
# from uainfo import ua_list
import pymysql


class MeituanSpider(object):
    def __init__(self):
        self.url = 'https://minsu.dianping.com/chengdu/pn{}/?dateBegin=20221101&dateEnd=20221102'
        # 计数,请求一个页面的次数,初始值为1
        self.mysql = pymysql.connect(host='localhost', database='tenders', port=3306, user='root',
                                         password='123456')
        self.cur = self.mysql.cursor()
        self.blog = 1
        # 随机取一个UA
   
        # 发送请求
    def get_html(self, url):
        # 在超时间内,对于失败页面尝试请求三次
        if self.blog <= 3:
            try:
                data = {'dateBegin': '20221101',
                        'dateEnd': '20221102'
                }
                headers = {'Cookie': '',
                            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3928.4 Safari/537.36',}
                res = requests.get(url=url, headers=headers,data=data, timeout=3)
                html = res.text
                return html
            except Exception as e:
                print(e)
                self.blog += 1
                self.get_html(url)

        # 解析提取数据
    def parse_html(self, url):
        html = self.get_html(url)
        if html:
            time.sleep(1)
            p = etree.HTML(html)
            # 基准xpath表达式-30个房源节点对象列表
            h_list = p.xpath('//div[@class="r-card-list v-stretch h-stretch"]/div[@class="r-card-list__item shrink-in-sm"]')
            # 所有列表节点对象
            for h in h_list:
                title1 = h.xpath('.//div[@class="product-card__title"]/text()')[0]
                address1 = h.xpath('.//div[@class="mt-2"]/text()')[0]
                url1 = 'https://minsu.dianping.com' + h.xpath('.//a[@class="product-card-container"]/@href')[0]
                configuration1 = h.xpath('.//div[@class="product-card__type-detail"]/div[1]/text()')[0]
                price1= h.xpath('.//span[@class ="product-card__price__latest"]/text()')[0]
                collections1 = h.xpath('.//span[@class="product-fav-count"]/text()')[0]
                # result = requests.get(url=url1, headers=self.get_header())
                # tree = etree.HTML(result.text)
                # print(tree)
                # time.sleep(1.0)
                # price = tree.xpath("//div[@class='price ']/span/text()")[0]
                data = {
                    'title': title1,
                    'urls': url1,
                    'address': address1,
                    'configuration': configuration1,
                    'collections': collections1,
                    'price': price1,
                    'unit': '元'
                    }

                print(data)
                self.save_mysql(data)

    def save_mysql(self, data):
        # str_sql = "insert into ftx values(0, '{}', '{}');".format(data['first_category'],data['second_category'])
        str_sql = "insert into meituan values(0, '{}', '{}', '{}', '{}', '{}', '{}', '{}');".format(
                data['title'],  data['urls'],data['address'], data['configuration'], data['collections'],
                data['price'], data['unit'])

        self.cur.execute(str_sql)
        self.mysql.commit()

    def __del__(self):
        self.cur.close()
        self.mysql.close()


        # 入口函数
    def run(self):
        try:
            for i in range(1,4):
                url = self.url.format(i)
                print(i)

                self.parse_html(url)
                time.sleep(random.randint(3, 5))
                # 每次抓取一页要初始化一次self.blog
                self.blog = 1
        except Exception as e:
            print('发生错误', e)


if __name__ == '__main__':
    spider = MeituanSpider()
    spider.run()

2.运行结果

 

 

标签:__,美团,民宿,爬取,pymysql,import,self
From: https://www.cnblogs.com/icekele/p/16849550.html

相关文章

  • python爬取公众号文章发布时间
    使用xpath取出来的是空,爬取到本地的html,时间的标签如下,内容也是是空的<emid="publish_time"class="rich_media_metarich_media_meta_text"></em>经过查找发现网页使......
  • 小说网页内容爬取
    近来闲来无事,看小说的时候发现都是垃圾流氓广告,突发奇想要不自己把小说内容给爬取下来?说干就干1、简介:所谓小说爬取无非就是对请求返回来的html内容进行解析获取到自己想......
  • 【C#】爬取百度贴吧帖子 通过贴吧名和搜索关键词
    背景:最近喜欢看百度贴吧,因为其内容大多都是吧友的真实想法表达等等原因。但是通过网页去浏览贴吧,始终觉得不够简介,浏览帖子的效率不高,自己就萌发了通过自己爬取贴吧感兴趣......
  • 爬取小说并拷贝到为xls格式
    importrequestsimportbs4importpandasaspddefl():foriinrange(30):dict={}book=soup.find_all('a',attrs={'class':'jt'})[i].tex......
  • python 爬虫 -----Bs4 爬取并且下载图片
    #1.拿到主页面主代码,拿到子页面连接地址,href#2.通过href拿到子页面内容,从子页面中找到图片的下载地址img->src#3.下载图片importrequestsfrombs4importBea......
  • 求大神解答:利用python爬取各县GDP结果为空,求大神看看我的代码问题在哪?
    目标url=红黑人口库代码importrequestsfromlxmlimportetreeimporttimeif__name__=='__main__':  url='https://pagead2.googlesyndication.com/getconfig/soda......
  • 爬取淘宝女装并可视化分析
    这次主要是爬虫实战+数据可视化分析:爬虫针对是淘宝的女装信息详细代码数据可以到我的gitee下载:爬取淘宝女装并可视化分析:基于爬虫,获取淘宝的商品信息,保存本地并进行可视......
  • Python爬取照片
    实例:爬取内蒙古科技大学校徽打开网站      1.引入requests模块   2.输入要请求的网站url   网址获取 3.发送请求头  user-agent的获......
  • python 爬取电影天堂
    代码如下:#1.定位到电影天堂必看片栏目#2.从其中提取到子页面的连接地址#3.请求子页面的连接地址并拿到下载地址importrequestsimportredomain="https://......
  • 2021-08-14美团算法面试题【数组实现二分、三数和、求n进制】
    一、二分查找publicstaticintsearch(int[]nums,inttarget){intleft=0,right=nums.length-1;while(left<=right){intmid=(l......