python爬虫爬取艺龙国际酒店信息

项目需要用到数据,在网上找了好久的数据都没有结果,就自己写了爬虫。没咋写过程序,为了简单都没有用函数。中间遇见了不少问题,首先爬虫只能爬取前十条信息。为了解决这个问题,上网搜了一些信息。网上说动态网页抓取可以用selenium。于是按照书本和网上的教程安装了selenium和phantomjs。但是问题仍然没有解决,后来试了下用匿名ip的方法,失败。接着添加了模拟下拉网页的代码。成功获取了第一页的30条信息。接着想办法模拟翻页,找了几行代码结果就成功了。这样我就可以爬取某一天纽约所有酒店的信息了。然后考虑连续爬取30天的信息。这个部分想了好久

给一张艺龙选择日期的截图
《python爬虫爬取艺龙国际酒店信息》
本来以为可以模拟点击,但是搞了一会不行
然后发现了可以直接输入日期。模拟输入。不得不赞selenium的强大
下面是源代码,不想说太多话

# -*- coding: utf-8 -*- 
from selenium import webdriver
#import urllib2
import time 

from bs4 import BeautifulSoup
#import urlparse
#service_args=['--proxy=127.0.0.1:9150','--proxy-type=socks5',]
datelist=['2017-4-4','2017-4-5','2017-4-6','2017-4-7','2017-4-8','2017-4-9','2017-4-10','2017-4-11',
          '2017-4-12','2017-4-13','2017-4-14','2017-4-15','2017-4-16','2017-4-17','2017-4-18','2017-4-19'
          '2017-4-20','2017-4-21','2017-4-22','2017-4-23','2017-4-24','2017-4-25','2017-4-26','2017-4-27','2017-4-28']
driver=webdriver.PhantomJS(executable_path=r'C:\Users\cimdy\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda2 (32-bit)\phantomjs')

driver.get('http://ihotel.elong.com/region_178293/')
time.sleep(2)
for date in datelist:
    driver.find_element_by_xpath("//input[@id='inDate']").send_keys(date)
    time.sleep(5) 
    page=0
    hotels_inf=[]
    while page<=5:
        times=10
        for i in range(times + 1):
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(5)
        pageSource=driver.page_source
        html_content=BeautifulSoup(pageSource,'lxml')
        hotels=html_content.findAll('div',{'class':'h_item clearfix'})
        print len(hotels)

        for hotel in hotels:
            single_hotel_inf=[]
            if 'hotelname' in hotel.attrs:
                single_hotel_inf.append(hotel.attrs['id'])
                single_hotel_inf.append(hotel.attrs['commentcount'])
                single_hotel_inf.append(hotel.attrs['hotelprice'])
                single_hotel_inf.append(hotel.attrs['hotelname'])
            hotels_inf.append(single_hotel_inf) 
        driver.find_element_by_xpath("//a[contains(text(),'下一页')]").click() # selenium的xpath用法,找到包含“下一页”的a标签去点击
        page = page + 1
        time.sleep(2) # 睡2秒让网页加载完再去读它的html代码
    with open(date+".txt","w") as f:
        for hotel_inf in hotels_inf:
            for hotel_attr in hotel_inf:
                print hotel_attr
                f.write(hotel_attr.encode('utf8')+' ')  
            f.write('\n')
    driver.get('http://ihotel.elong.com/region_178293/')
    time.sleep(2)
driver.close()

下面是运行结果展示
《python爬虫爬取艺龙国际酒店信息》
还有许多细节在程序里,比如自动存储文件,用字符串做了个list,遍历list

    原文作者:daisyliudi
    原文地址: https://blog.csdn.net/u013496193/article/details/68223226
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞