Python_大众点评网站数据爬虫


目标:
爬取大众点评某地区的酒店信息,包括酒店名,平均价格,评价人数,标签等,并将其写入txt,导入数据库。
所用模块:urllib,urllib2,re,BeautifulSoup
大致步骤:
(1)获取页面所在首页url,及相应的headers;
(2)页面解析,获取信息,写入txt,并尝试获取下一页的url,若得到,则以此更新url,继续(2),若找不到,则停止,进入(3);

(3)将所得到的txt文档中的数据一次性导入mysql。


#-*-coding:utf-8-*-
'''
created by zwg in 2016-10-15
'''
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import urllib
import urllib2
import re
import copy
from bs4 import BeautifulSoup
import MySQLdb

class get_data:
    def get_html(self,url,headers):
        opener=urllib2.build_opener()
        headers_copy=headers.items()
        for i in headers_copy:
            opener.addheaders=[i]
        urllib2.install_opener(opener)
        self.url=url
        page=opener.open(url)
        self.html=page.read()
        self.soup=BeautifulSoup(self.html,'lxml',from_encoding='utf-8')
        self.opener=opener


    def get_nextpage(self):
        basic_url='http://www.dianping.com'
        next_url=self.soup.find_all('a',class_='next')
        new_url=next_url[0]['href']
        self.url=basic_url+new_url
        self.html=self.opener.open(self.url)
        self.soup=BeautifulSoup(self.html,'lxml',from_encoding='utf-8')
    def get_one_data(self):
        hotel_li = self.soup.find_all('li', class_='hotel-block')
        pattern1 = re.compile('''"title":"(.+)"''')
        info = []
        for i in hotel_li:
            s = i['data-hippo']
            s1 = pattern1.findall(s)[0]
            name = s1  # 酒店名
            p_class = i.find_all('p', class_='hotel-tags')[0]
            p11 = p_class.find_all('span')
            comment = ''
            for j in p11:
                comment = comment + j.string + ','
            comment=comment[0:len(comment)-1]
            p_price = i.find_all('strong')[0]
            price = p_price.string  # 酒店价格
            price.replace(' ', '')
            if price == '\n':
                price = 'None'
            p_people = i.find_all('a', class_='comments')[0]
            number = p_people.string  # 评论人数
            number = number.replace('(', '')
            number = number.replace(')', '')
            number = number.replace(' ', '')
            if not number.isdigit():
                number = 'None'
            p=i.find_all('p',class_='place')
            place=str(p[0].a.string)
            info.append((name, price, place, number, comment))
            print '%-20s%-10s%-10s%-5s%s' % (name, price, place, number, comment)
        self.info=info
    def write_to_txt(self, file1):
        for i in self.info:
            a, b, c, d, e = i
            s = ('%s\t%s\t%s\t%s\t%s\n') % (a, b, c, d, e)
            file1.writelines(s)
    def get_all_data(self,file1):
        for i in xrange(5):
            self.get_one_data()
            self.write_to_txt(file1)
            self.get_nextpage()





url='http://www.dianping.com/guangzhou/hotel/p1'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
                      '(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}
G=get_data()
G.get_html(url,headers)
file1 = file('dazhong.txt', 'a+')
conn=MySQLdb.connect('127.0.0.1','root','1234','school',)
cursor=conn.cursor()
conn.set_character_set('utf8')
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
G.get_all_data(file1)
sql="load data local infile 'D:/Python/web_crawler/dazhong.txt' " \
    "into table hotel_info fields terminated by '\t'"
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

实现通过,Done!

Python爬虫是一种自动化抓取网页数据的程序,使用Python语言可以编写出各种功能强大的爬虫。在编写爬虫程序时,通常会用到如`requests`库进行网络请求,`BeautifulSoup`或`lxml`等库来解析HTML页面。 以下是一个简单的Python爬虫示例,用于爬取大众点评的某一页数据。请注意,由于网站的结构可能随时更改,以下代码可能需要根据实际情况进行调整。 ```python import requests from bs4 import BeautifulSoup # 目标URL,这里需要替换成实际要爬取的大众点评页面地址 url = 'https://www.dianping.com/某城市/某分类' # 发送HTTP请求 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) # 检查请求是否成功 if response.status_code == 200: # 使用BeautifulSoup解析HTML soup = BeautifulSoup(response.text, 'lxml') # 提取信息,这里以提取店铺名称和评分为例 list = [] for item in soup.find_all('div', class_='店铺信息类名'): # 需要根据实际的HTML结构替换'店铺信息类名' name = item.find('a', class_='店铺名称类名').text # 替换'店铺名称类名' rating = item.find('span', class_='评分类名').text # 替换'评分类名' list.append({'name': name, 'rating': rating}) # 打印提取的信息 for store in list: print(store) else: print("请求失败,状态码:", response.status_code) ``` 在实际使用中,大众点评网站可能有反爬虫措施,如动态加载内容、验证码、IP限制等。这时可能需要使用更高级的技术如Selenium进行模拟浏览器操作,或者设置合适的请求间隔、使用代理等方法。 使用爬虫时,请遵守相关法律法规和网站的使用协议,不要进行任何侵犯隐私或违法的行为。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值