xiecheng_spider

本文介绍了一种使用Python和Selenium库抓取携程民宿信息的方法,包括安装浏览器驱动、使用XPath解析网页元素、多窗口操作及数据保存至Excel的全过程。

xiecheng_spider携程民宿爬虫

获取URL

由于携程网页由CSS编写,因此我们需要使用浏览器去跳转页面,这里我需要做一些准备工作

1.安装谷歌浏览器驱动,链接如下。安装成功后要放在PATH路径下

http://npm.taobao.org/mirrors/chromedriver/

2.安装环境,这里我用的Python3.7

# 我们需要使用其中的模块
pip install selenium

接下来我们来进行代码实现

首先引入一些需要的模块和html的URL

#!/usr/bin/env python
# coding=utf-8
import sys
import time
import json
import xlsxwriter
from selenium import webdriver

url = "https://inn.ctrip.com/onlineinn/list?checkin=2019-06-15&checkout=2019-06-16&cityid=5&cityname=%E5%93%88%E5%B0%94%E6%BB%A8&channelid=211"
# 定义一个字典稍后存储数据的时候用
items = []

接下来我们需要使用谷歌浏览器进行页面操作

#!/usr/bin/env python
# coding=utf-8
import sys
import time
import json
import xlsxwriter
from selenium import webdriver

url = "https://inn.ctrip.com/onlineinn/list?checkin=2019-06-15&checkout=2019-06-16&cityid=5&cityname=%E5%93%88%E5%B0%94%E6%BB%A8&channelid=211"
items = []

# 谷歌驱动
def chrome_driver(url):
    driver = webdriver.Chrome()
    driver.get(url)
    return driver

接下来我们了解一下Xpath

XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。

通过Xpath我们就能够获取相应的数据

#!/usr/bin/env python
# coding=utf-8
import sys
import time
import json
import xlsxwriter
from selenium import webdriver

url = "https://inn.ctrip.com/onlineinn/list?checkin=2019-06-15&checkout=2019-06-16&cityid=5&cityname=%E5%93%88%E5%B0%94%E6%BB%A8&channelid=211"
items = []

# 谷歌驱动
def chrome_driver(url):
    driver = webdriver.Chrome()
    driver.get(url)
    return driver

# 获取信息
def get_items(driver):
    time.sleep(1)
    # 展开全部
    show_all = driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[2]/div[4]')
    show_all.click()
    # 字典获取
    feed_item = {
        'info':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[1]').text,
        'type_of_house':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[1]').text,
        'num_of_people':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[2]/span[1]').text,
        'num_of_bed':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[3]/span[1]').text,
        'if_cook':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[3]').text,
        'if_swim':'No',
        'if_supermarket':'No',
        'locate':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[3]/span').text,
        'url':driver.current_url,
        'price':driver.find_element_by_class_name('txt-price').text
    }
    if driver.find_elements_by_class_name('item-device-0507') != []:
        feed_item['id_swim'] = 'Have swim pool'
    if driver.find_elements_by_class_name("item-device-0501") != []:
        feed_item['if_supermarket'] = "Have super market"
    items.append(feed_item) # 将数据保存到items字典中

由于我们找不到每个hotel的相应URL,因此我们需要浏览器进行虚拟操作来帮助我们

#!/usr/bin/env python
# coding=utf-8
import sys
import time
import json
import xlsxwriter
from selenium import webdriver

url = "https://inn.ctrip.com/onlineinn/list?checkin=2019-06-15&checkout=2019-06-16&cityid=5&cityname=%E5%93%88%E5%B0%94%E6%BB%A8&channelid=211"
items = []

# 谷歌驱动
def chrome_driver(url):
    driver = webdriver.Chrome()
    driver.get(url)
    return driver

# 获取信息
def get_items(driver):
    time.sleep(1)
    # 展开全部
    show_all = driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[2]/div[4]')
    show_all.click()
    # 字典获取
    feed_item = {
        'info':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[1]').text,
        'type_of_house':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[1]').text,
        'num_of_people':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[2]/span[1]').text,
        'num_of_bed':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[3]/span[1]').text,
        'if_cook':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[3]').text,
        'if_swim':'No',
        'if_supermarket':'No',
        'locate':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[3]/span').text,
        'url':driver.current_url,
        'price':driver.find_element_by_class_name('txt-price').text
    }
    if driver.find_elements_by_class_name('item-device-0507') != []:
        feed_item['id_swim'] = 'Have swim pool'
    if driver.find_elements_by_class_name("item-device-0501") != []:
        feed_item['if_supermarket'] = "Have super market"
    items.append(feed_item) # 将数据保存到items字典中

# 信息组合
def get_all_infos(driver):
    cnt = 0
    time.sleep(3)
    click_items = driver.find_elements_by_class_name("list-photo")
    for each in click_items:
        cnt = cnt + 1
        each.click() #浏览器跳转
        handle = driver.window_handles
        driver.switch_to.window(handle[1]) #浏览器选择窗口
        time.sleep(1)
        name = driver.find_elements_by_class_name("tit")
        if (len(name) == 0):
            driver.close()
            driver.switch_to.window(handle[0])
            continue
        print (str(cnt) + "." + name[0].text)
        get_items(driver)
        driver.close()
        driver.switch_to.window(handle[0])
    return 1;

在获得到所有数据之后我们需要将其放入excel表格中

在这之前我们需要引入相应的模块

pip install xlsxwriter
#!/usr/bin/env python
# coding=utf-8
import sys
import time
import json
import xlsxwriter
from selenium import webdriver

url = "https://inn.ctrip.com/onlineinn/list?checkin=2019-06-15&checkout=2019-06-16&cityid=5&cityname=%E5%93%88%E5%B0%94%E6%BB%A8&channelid=211"
items = []

# 谷歌驱动
def chrome_driver(url):
    driver = webdriver.Chrome()
    driver.get(url)
    return driver

# 获取信息
def get_items(driver):
    time.sleep(1)
    # 展开全部
    show_all = driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[2]/div[4]')
    show_all.click()
    # 字典获取
    feed_item = {
        'info':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[1]').text,
        'type_of_house':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[1]').text,
        'num_of_people':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[2]/span[1]').text,
        'num_of_bed':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[3]/span[1]').text,
        'if_cook':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[3]').text,
        'if_swim':'No',
        'if_supermarket':'No',
        'locate':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[3]/span').text,
        'url':driver.current_url,
        'price':driver.find_element_by_class_name('txt-price').text
    }
    if driver.find_elements_by_class_name('item-device-0507') != []:
        feed_item['id_swim'] = 'Have swim pool'
    if driver.find_elements_by_class_name("item-device-0501") != []:
        feed_item['if_supermarket'] = "Have super market"
    items.append(feed_item) # 将数据保存到items字典中

# 信息组合
def get_all_infos(driver):
    cnt = 0
    time.sleep(3)
    click_items = driver.find_elements_by_class_name("list-photo")
    for each in click_items:
        cnt = cnt + 1
        each.click()
        handle = driver.window_handles
        driver.switch_to.window(handle[1])
        time.sleep(1)
        name = driver.find_elements_by_class_name("tit")
        if (len(name) == 0):
            driver.close()
            driver.switch_to.window(handle[0])
            continue
        print (str(cnt) + "." + name[0].text)
        get_items(driver)
        driver.close()
        driver.switch_to.window(handle[0])
    return 1;

# 保存信息
def save_to_excel(data):
    workbook = xlsxwriter.Workbook('./xiecheng_spider.xlsx')
    worksheet = workbook.add_worksheet()

    # 设定格式,等号左边格式名称自定义,字典中格式为指定选项
    # bold:加粗,num_format:数字格式
    bold_format = workbook.add_format({'bold': True})
    #money_format = workbook.add_format({'num_format': '$#,##0'})
    #date_format = workbook.add_format({'num_format': 'mmmm d yyyy'})

    # 将二行二列设置宽度为15(从0开始)
    # worksheet.set_column(1, 1, 15)

    # 用符号标记位置,例如:A列1行
    worksheet.write('A1', 'info', bold_format)
    worksheet.write('B1', 'type_of_house', bold_format)
    worksheet.write('C1', 'num_of_people', bold_format)
    worksheet.write('D1', 'num_of_bed', bold_format)
    worksheet.write('E1', 'if_cook', bold_format)
    worksheet.write('F1', 'if_swim', bold_format)
    worksheet.write('G1', 'if_supermarket', bold_format)
    worksheet.write('H1', 'locate', bold_format)
    worksheet.write('I1', 'url', bold_format)
    worksheet.write('J1', 'price', bold_format)

    #写内容
    for i in range(len(data)):
        worksheet.write_string(i + 1, 0, data[i]['info'])
        worksheet.write_string(i + 1, 1, data[i]['type_of_house'])
        worksheet.write_string(i + 1, 2, data[i]['num_of_people'])
        worksheet.write_string(i + 1, 3, data[i]['num_of_bed'])
        worksheet.write_string(i + 1, 4, data[i]['if_cook'])
        worksheet.write_string(i + 1, 5, data[i]['if_swim'])
        worksheet.write_string(i + 1, 6, data[i]['if_supermarket'])
        worksheet.write_string(i + 1, 7, data[i]['locate'])
        worksheet.write_string(i + 1, 8, data[i]['url'])
        worksheet.write_string(i + 1, 9, data[i]['price'])
    workbook.close()

最后运用主函数进行总体调用

完整代码:

#!/usr/bin/env python
# coding=utf-8
import sys
import time
import json
import xlsxwriter
from selenium import webdriver

url = "https://inn.ctrip.com/onlineinn/list?checkin=2019-06-15&checkout=2019-06-16&cityid=5&cityname=%E5%93%88%E5%B0%94%E6%BB%A8&channelid=211"
items = []

# 谷歌驱动
def chrome_driver(url):
    driver = webdriver.Chrome()
    driver.get(url)
    return driver

# 获取信息
def get_items(driver):
    time.sleep(1)
    # 展开全部
    show_all = driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[2]/div[4]')
    show_all.click()
    # 字典获取
    feed_item = {
        'info':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[1]').text,
        'type_of_house':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[1]').text,
        'num_of_people':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[2]/span[1]').text,
        'num_of_bed':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[3]/span[1]').text,
        'if_cook':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[2]/div[3]/div[1]/div[1]/span[3]').text,
        'if_swim':'No',
        'if_supermarket':'No',
        'locate':driver.find_element_by_xpath('//*[@id="__next"]/div/div/div[1]/div/div[1]/div[3]/span').text,
        'url':driver.current_url,
        'price':driver.find_element_by_class_name('txt-price').text
    }
    if driver.find_elements_by_class_name('item-device-0507') != []:
        feed_item['id_swim'] = 'Have swim pool'
    if driver.find_elements_by_class_name("item-device-0501") != []:
        feed_item['if_supermarket'] = "Have super market"
    items.append(feed_item) # 将数据保存到items字典中

# 信息组合
def get_all_infos(driver):
    cnt = 0
    time.sleep(3)
    click_items = driver.find_elements_by_class_name("list-photo")
    for each in click_items:
        cnt = cnt + 1
        each.click()
        handle = driver.window_handles
        driver.switch_to.window(handle[1])
        time.sleep(1)
        name = driver.find_elements_by_class_name("tit")
        if (len(name) == 0):
            driver.close()
            driver.switch_to.window(handle[0])
            continue
        print (str(cnt) + "." + name[0].text)
        get_items(driver)
        driver.close()
        driver.switch_to.window(handle[0])
    return 1;

# 保存信息
def save_to_excel(data):
    workbook = xlsxwriter.Workbook('./xiecheng_spider.xlsx')
    worksheet = workbook.add_worksheet()

    # 设定格式,等号左边格式名称自定义,字典中格式为指定选项
    # bold:加粗,num_format:数字格式
    bold_format = workbook.add_format({'bold': True})
    #money_format = workbook.add_format({'num_format': '$#,##0'})
    #date_format = workbook.add_format({'num_format': 'mmmm d yyyy'})

    # 将二行二列设置宽度为15(从0开始)
    # worksheet.set_column(1, 1, 15)

    # 用符号标记位置,例如:A列1行
    worksheet.write('A1', 'info', bold_format)
    worksheet.write('B1', 'type_of_house', bold_format)
    worksheet.write('C1', 'num_of_people', bold_format)
    worksheet.write('D1', 'num_of_bed', bold_format)
    worksheet.write('E1', 'if_cook', bold_format)
    worksheet.write('F1', 'if_swim', bold_format)
    worksheet.write('G1', 'if_supermarket', bold_format)
    worksheet.write('H1', 'locate', bold_format)
    worksheet.write('I1', 'url', bold_format)
    worksheet.write('J1', 'price', bold_format)

    #写内容
    for i in range(len(data)):
        worksheet.write_string(i + 1, 0, data[i]['info'])
        worksheet.write_string(i + 1, 1, data[i]['type_of_house'])
        worksheet.write_string(i + 1, 2, data[i]['num_of_people'])
        worksheet.write_string(i + 1, 3, data[i]['num_of_bed'])
        worksheet.write_string(i + 1, 4, data[i]['if_cook'])
        worksheet.write_string(i + 1, 5, data[i]['if_swim'])
        worksheet.write_string(i + 1, 6, data[i]['if_supermarket'])
        worksheet.write_string(i + 1, 7, data[i]['locate'])
        worksheet.write_string(i + 1, 8, data[i]['url'])
        worksheet.write_string(i + 1, 9, data[i]['price'])
    workbook.close()

if __name__ == "__main__":
    driver = chrome_driver(url)
    while True:
        ret = get_all_infos(driver)
        save_to_excel(items)
        if (ret == 1):
            sys.exit()
            next = driver.find_element_by_class_name("item-next")
            next.click()
        if (next == 0):
            break

运行部分效果图

【电能质量扰动】基于ML和DWT的电能质量扰动分类方法研究(Matlab实现)内容概要:本文研究了一种基于机器学习(ML)和离散小波变换(DWT)的电能质量扰动分类方法,并提供了Matlab实现方案。首先利用DWT对电能质量信号进行多尺度分解,提取信号的时频域特征,有效捕捉电压暂降、暂升、中断、谐波、闪变等常见扰动的关键信息;随后结合机器学习分类器(如SVM、BP神经网络等)对提取的特征进行训练与分类,实现对不同类型扰动的自动识别与准确区分。该方法充分发挥DWT在信号去噪与特征提取方面的优势,结合ML强大的模式识别能力,提升了分类精度与鲁棒性,具有较强的实用价值。; 适合人群:电气工程、自动化、电力系统及其自动化等相关专业的研究生、科研人员及从事电能质量监测与分析的工程技术人员;具备一定的信号处理基础和Matlab编程能力者更佳。; 使用场景及目标:①应用于智能电网中的电能质量在线监测系统,实现扰动类型的自动识别;②作为高校或科研机构在信号处理、模式识别、电力系统分析等课程的教学案例或科研实验平台;③目标是提高电能质量扰动分类的准确性与效率,为后续的电能治理与设备保护提供决策依据。; 阅读建议:建议读者结合Matlab代码深入理解DWT的实现过程与特征提取步骤,重点关注小波基选择、分解层数设定及特征向量构造对分类性能的影响,并尝试对比不同机器学习模型的分类效果,以全面掌握该方法的核心技术要点。
### 处理或使用 `xiecheng_ugc` CSV 文件的方法 为了有效处理或使用 `xiecheng_ugc` CSV 文件,可以采用一系列的数据预处理和技术手段来实现数据的有效利用。以下是具体的操作方式: #### 读取CSV文件 首先需要加载CSV文件到内存中以便后续操作。Python中的Pandas库提供了强大的DataFrame结构用于高效地存储和操作表格型数据。 ```python import pandas as pd # 加载CSV文件至DataFrame对象 df = pd.read_csv('path_to_xiecheng_ugc.csv') ``` #### 数据清洗 确保数据质量是数据分析的重要前提条件之一。对于UGC(用户生成内容),尤其需要注意去除噪声信息以及填补缺失值等问题[^1]。 ```python # 去除重复项 df.drop_duplicates(inplace=True) # 查看并处理缺失值 print(df.isnull().sum()) df.fillna(value='default_value', inplace=True) # 或者根据实际情况选择其他填充策略 ``` #### 主题抽取与情感分析 针对在线民宿评论的特点,在完成初步清理之后可进一步开展主题模型构建及情绪倾向评估等工作。这有助于深入理解用户的反馈意见及其背后的情感态度变化趋势。 ```python from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import LatentDirichletAllocation # 提取TF-IDF特征向量 vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, stop_words='english') X = vectorizer.fit_transform(df['comments']) # 应用LDA算法进行主题建模 lda = LatentDirichletAllocation(n_components=10, random_state=42) lda.fit(X) # 输出前n个最能代表各主题的关键词 def display_topics(model, feature_names, no_top_words): for topic_idx, topic in enumerate(model.components_): print(f"Topic {topic_idx}:") print(" ".join([feature_names[i] for i in topic.argsort()[:-no_top_words - 1:-1]])) display_topics(lda, vectorizer.get_feature_names_out(), 10) # 进行情感分类 from textblob import TextBlob sentiments = [] for comment in df['comments']: blob = TextBlob(comment) sentiments.append(blob.sentiment.polarity) df['sentiment'] = sentiments ``` 通过上述流程能够较为全面地解析来自携程平台上的用户评价信息,并从中提炼有价值的知识供决策支持之用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值