大连指令数据集的创建--数据收集与预处理_02

devtools/2025/2/27 13:32:55/

1.去哪儿爬虫

  • 编程语言:Python
  • 爬虫框架:Selenium(用于浏览器自动化)
  • 解析库:BeautifulSoup(用于解析HTML)

2.爬虫策略

  • 目标网站:去哪儿(https://travel.qunar.com/travelbook/list.htm?order=hot_heat)
  • 目标数据:大连的旅游攻略
  • 流程概述
    1. 打开去哪儿旅游攻略并进行搜索。
    2. 提取搜索结果页面中旅游攻略的链接。
    3. 分别访问每个旅游攻略页面,提取内容并按照json格式保存到本地文件。

3.获取旅游攻略链接

3.1导入库

python">import re
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from bs4 import BeautifulSoup

3.2配置文件路径和ChromeDriver路径,根据自己的Chrome的chromedriver.exe的路径配置ChromeDriver路径,根据自己存放链接的位置配置文件路径

python"># 配置文件路径和ChromeDriver路径
file_path = 'D:\\Pycharm\\space\\Qunaer\\去哪儿大连链接.txt'//根据实际位置设置路径
chrome_driver_path = "D:\\chromedriver\\chromedriver.exe"//根据实际位置设置路径

3.3初始化Selenium WebDriver

python">s = Service(chrome_driver_path)
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(service=s, options=options)

3.4获取去哪儿大连的攻略链接,并存储在txt文档中。

python"># 打开去哪儿攻略页面
driver.get("https://travel.qunar.com/travelbook/list.htm?order=hot_heat")wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.XPATH, '/html/body/div[3]/div/div[2]/div[1]/div[1]/input[1]')))start_input = driver.find_element(By.XPATH, '/html/body/div[3]/div/div[2]/div[1]/div[1]/input[1]')
start_input.send_keys('大连')
time.sleep(1)
start_input = driver.find_element(By.CLASS_NAME, 'sub_btn')
start_input.click()
time.sleep(3)
soup = BeautifulSoup(driver.page_source, 'html.parser')
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'b_paging')))
paging_div = soup.find('div', class_='b_paging')
max_page = 0
if paging_div.text or paging_div.find_elements(By.TAG_NAME, 'a'):soup = BeautifulSoup(driver.page_source, 'html.parser')max_page = 0for a_tag in paging_div.find_all('a'):if 'data-beacon' in a_tag.attrs and a_tag['data-beacon'] == 'click_result_page':href = a_tag['href']page_number = int(href.split('/')[-1].split('.')[0])max_page = max(max_page, page_number)print(f"Maximum page number: {max_page} {href}")pattern = re.compile(r'(\d+)\.htm$')href = pattern.sub('', href)for i in range(max_page):link = "https:" + href + str(i+1) + ".htm"time.sleep(1)driver.get(link)soup = BeautifulSoup(driver.page_source, 'html.parser')wait = WebDriverWait(driver, 10)wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'list_item')))list_items = soup.find_all('li', {'class': 'list_item'})for item in list_items:data_url = item.get('data-url')if data_url:with open(file_path, 'a', encoding='utf-8') as file:file.write(data_url + '\n')else:print(f"No data-url found for this <li> element.")else:print("No <ul> element with class b_strategy_list found.")
else:print("The b_paging div is empty or doesn't contain any anchor tags.")

3.5运行结果:

4.获取并处理旅游攻略内容

4.1导入库

python">import json
import time
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

4.2一个字典和三个函数的定义

先上代码,再分析定义函数的功能和作用。

python">chinese_months = {1: '一月',2: '二月',3: '三月',4: '四月',5: '五月',6: '六月',7: '七月',8: '八月',9: '九月',10: '十月',11: '十一月',12: '十二月'
}def remove_after_comment(text):index = text.find("【备注】")if index != -1:return text[:index]else:return textdef get_season(month):if 3 <= month <= 5:return '春天'elif 6 <= month <= 8:return '夏天'elif 9 <= month <= 11:return '秋天'else:return '冬天'def change(text):if '/' in text:try:date_obj = datetime.strptime(text, '%Y/%m/%d')month_name = chinese_months[date_obj.month]season = get_season(date_obj.month)result_list.append(f'{month_name}')result_list.append(f'{season}')except ValueError:passelif text.isdigit():if int(text) < 99:result_list.append(f'{text}天')else:result_list.append(f'{text}元')else:if text not in result_list:result_list.append(text)

以下是对这四个函数的详细解释和分析

 1. `chinese_months` 字典
功能:将公历月份(数字1-12)映射为中文月份名称。
作用:提供标准化的月份翻译,符合中文习惯。

2. `remove_after_comment` 函数
功能:删除文本中“【备注】”及其后的内容。
作用:清理数据中的注释信息,保留主文本。

3. `get_season` 函数
功能:根据月份返回对应季节。
作用:将月份映射为中文季节名称,符合中国常见的气象季节划分(3-5月为春,6-8月为夏等)。但需注意,中国幅员辽阔,实际季节可能因地而异,此处为通用逻辑。

 4. `change` 函数
功能:多条件文本转换器,处理日期、数字和其他文本。
作用:
(1)日期处理:识别形如 `YYYY/MM/DD` 的日期,提取中文月份和季节(依赖 `chinese_months` 和 `get_season`)。例如,输入 `"2025/02/25"` → 输出 `["二月", "冬天"]`。
(2)数字处理:
     - 小于99的数字添加“天”(如 `30` → `"30天"`,表示天数)。
     - 大于等于99的数字添加“元”(如 `100` → `"100元"`,表示金额)。
(3)其他文本:直接保留唯一值(去重)。

4.3配置文件路径和ChromeDriver路径,根据自己的Chrome的chromedriver.exe的路径配置ChromeDriver路径,根据自己存放链接的位置配置文件路径。

python"># 配置文件路径和ChromeDriver路径
file_path = 'D:\\Pycharm\\space\\Qunaer\\去哪儿大连链接.txt'  # 保存内容的文件路径
chrome_driver_path = "D:\\chromedriver\\chromedriver.exe"  # ChromeDriver路径

4.4初始化Selenium WebDriver

python">s = Service(chrome_driver_path)
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(service=s, options=options)

4.5打开3.5中生成的“去哪儿大连链接.txt”文件,获取链接,进一步处理,爬取大连旅游攻略内容。

python">with open(file_path, 'r') as file:for line in file:result_list = []line = line.strip()last_part = line.rsplit('/', 1)[-1]print(last_part)time.sleep(1)driver.get("https://travel.qunar.com/travelbook/note/" + last_part)driver.maximize_window()try:wait = WebDriverWait(driver, 10)wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'foreword_list')))except TimeoutException:continuesoup = BeautifulSoup(driver.page_source, 'html.parser')ul = soup.find('ul', {'class': 'foreword_list'})print(ul)soup1 = BeautifulSoup(str(ul), 'html.parser')data_elements = soup1.find_all('span', {'class': 'data'})for data_element in data_elements:for text in data_element.stripped_strings:change(text)inputxt = ''for r in result_list:inputxt += '#'inputxt += str(r)text_element = soup.find('div', class_='e_main')text_content = text_element.get_text(strip=True, separator='\n')data = {'instruction': inputxt,'summary': '','output': remove_after_comment(text_content)}with open('D:\\Pycharm\\space\\Qunaer\\去哪儿大连.json', 'a', encoding='utf-8') as file:json.dump(data, file, ensure_ascii=False, indent=4)file.write('\n')time.sleep(3)driver.quit()

4.6运行结果

4.7工程文件夹,有两个python文件,一个是3中的获取旅游攻略链接,一个是4中的获取并处理旅游攻略内容


http://www.ppmy.cn/devtools/163073.html

相关文章

大模型基础概念之神经网络宽度

在大模型中,神经网络宽度是提升模型容量的核心手段之一,与深度、数据规模共同构成性能的三大支柱。合理增加宽度可显著增强模型表达能力,但需结合正则化、硬件优化和结构设计进行平衡。未来趋势可能包括动态宽度调整、稀疏化宽度设计(如MoE)以及更高效宽度-深度复合缩放策…

【p-camera-h5】 一款开箱即用的H5相机插件,支持拍照、录像、动态水印与样式高度定制化。

【开源推荐】p-camera-h5&#xff1a;一款轻量级H5相机插件开发实践 一、插件背景 在Web开发中&#xff0c;原生摄像头功能的集成往往面临以下痛点&#xff1a; 浏览器兼容性问题视频流与水印叠加实现复杂移动端适配困难功能定制成本高 为此&#xff0c;p-camera-h5 —— 一…

巨控科技的GRM550元出魔抗实现PLC远程下载与维护方案:工业自动化的高效解决方案

巨控科技PLC远程下载与维护方案&#xff1a;工业自动化的高效解决方案 在工业自动化领域&#xff0c;设备的高效维护与快速调试是保障生产连续性的关键。巨控科技推出的PLC远程下载与维护方案&#xff0c;凭借其先进的技术和广泛兼容性&#xff0c;成为企业实现设备远程管理的…

如何进行OceanBase 运维工具的部署和表性能优化

本文来自OceanBase 用户的实践分享 随着OceanBase数据库应用的日益深入&#xff0c;数据量不断攀升&#xff0c;单个表中存储数百万乃至数千万条数据的情况变得愈发普遍。因此&#xff0c;部署专门的运维工具、实施针对性的表性能优化策略&#xff0c;以及加强指标监测工作&…

【Java项目】基于Spring Boot的简历系统

【Java项目】基于Spring Boot的简历系统 技术简介&#xff1a;采用Spring Boot框架、Java技术、MySQL数据库等实现。 系统简介&#xff1a;系统主要实现了管理员模块、用户模块二大部分。管理员登录进入简历系统可以查看首页、个人中心、用户管理、简历模板管理、模板类型管理、…

DeepSeek开源DeepGEMM:高效 FP8 GEMM 核心与优化技术

人工智能咨询培训老师叶梓 转载标明出处 想要掌握如何将大模型的力量发挥到极致吗&#xff1f;叶老师带您深入了解 Llama Factory —— 一款革命性的大模型微调工具&#xff08;限时免费&#xff09;。 1小时实战课程&#xff0c;您将学习到如何轻松上手并有效利用 Llama Facto…

kiln微调大模型-使用deepseek R1去训练一个你的具备推理能力的chatGPT 4o

前言 随着deepseek的爆火&#xff0c;对于LLM的各种内容也逐渐步入我的视野&#xff0c;我个人认为&#xff0c;可能未来很长一段时间&#xff0c;AI将持续爆火&#xff0c;进入一段时间的井喷期&#xff0c;AI也会慢慢的走入我们每个家庭之中&#xff0c;为我们的生活提供便利…

Linux 文件操作与 Socket 编程核心知识详解

Linux 文件操作与 Socket 编程核心知识详解 一、Linux 文件与 Socket 的统一性 1.1 核心设计理念 在 Linux 系统中&#xff0c;秉持"一切皆文件"的设计理念&#xff1a; 所有 I/O 设备&#xff08;常规文件、网络 socket、外设等&#xff09;均被抽象为文件统一通…