|
<
用python爬与来哪女纪行攻略为十月假期做筹办。。。爬虫之路,永无尽头!
热热烈闹的开教季又去了,小同伴们又能够正在一同游玩了,不合错误是正在一同进修了,哈哈。
再过几周便是国庆假期,想一想依旧很激动的,我决议给各人做个纪行爬虫,各人早做筹办。。嘿嘿
代码操作展现:
今日目的地点:https://travel.qunar.com/place/
开辟状况:
windows10
python3.6
开辟东西:
pycharm
库:
tkinter、re、os、lxml、threading、xlwt、xlrd
1.起首先将全国一切的都会称号战id拿到
2.左击查抄,停止抓包,找到数据地点的包
3.收收恳求,获得呼应,剖析呼应
- # 收收恳求,获得呼应,剖析呼应
- response = session.get(self.start_url, headers=self.headers).html
- # 提与一切目标天(都会)的url
- city_url_list = response.xpath(
- '//*[@id="js_destination_recommend"]/div[2]/div[1]/div[2]/dl/dd/div/ul/li/a/@href')
- city_id_list = [''.join(re.findall(r'-cs(.*?)-', i)) for i in city_url_list]
- # 提与一切的都会称号
- city_name_list = response.xpath(
- '//*[@id="js_destination_recommend"]/div[2]/div[1]/div[2]/dl/dd/div/ul/li/a/text()')
复造代码 4.随机面一个都会,进进该都会,检察纪行攻略,本文选的是上海
5.停止抓包,查找需求的疑息
- # 提与纪行做者
- author_list = html.xpath('//span[@class="user_name"]/a/text()')
- # 动身工夫
- date_list = html.xpath('//span[@class="date"]/text()')
- # 玩耍工夫
- days_list = html.xpath('//span[@class="days"]/text()')
- # 浏览量
- read_list = html.xpath('//span[@class="icon_view"]/span/text()')
- # 面赞量
- like_count_list = html.xpath('//span[@class="icon_love"]/span/text()')
- # 批评量
- icon_list = html.xpath('//span[@class="icon_comment"]/span/text()')
- # 纪行地点
- text_url_list = html.xpath('//h3[@class="tit"]/a/@href')
复造代码 6.停止翻页抓包,第两页为同步减载
7.正在上一张图中面击Headers,获得纪行攻略的恳求地点
如许思绪是否是明晰一面,去察看一下恳求地点https://travel.qunar.com/place/api/html/books/dist/299878?sortField=0&pageSize=10&page=2
其中299878是上海都会的id page是页数
源码展现:
- # !/usr/bin/nev python# -*-coding:utf8-*-import tkinter as tkimport refrom lxml import etreeimport tkinter.messagebox as msgboxfrom requests_html import HTMLSessionfrom threading import Threadimport os, xlwt, xlrdfrom xlutils.copy import copysession = HTMLSession()class TKSpider(object): def __init__(self): # 界说轮回前提 self.is_running = True # 界说肇端的页码 self.start_page = 1 """界说可视化窗心,并设置窗心战主题巨细规划""" self.window = tk.Tk() self.window.title('爬虫数据收罗') self.window.geometry('1000x800') """创立label_user按钮,取仿单""" self.label_user = tk.Label(self.window, text='请挑选都会输进序号:', font=('Arial', 12), width=30, height=2) self.label_user.pack() """创立label_user联系关系输进""" self.entry_user = tk.Entry(self.window, show=None, font=('Arial', 14)) self.entry_user.pack(after=self.label_user) """创立Text富文本框,用于按钮操作成果的展现""" # 界说富文本框滑动条 scroll = tk.Scrollbar() # 放到窗心的右边, 加添Y横曲标的目的 scroll.pack(side=tk.RIGHT, fill=tk.Y) self.text1 = tk.Text(self.window, font=('Arial', 12), width=75, height=20) self.text1.pack() # 两个控件联系关系 scroll.config(command=self.text1.yview) self.text1.config(yscrollcommand=scroll.set) """界说按钮1,绑定触收变乱办法""" self.button_1 = tk.Button(self.window, text='下载纪行', font=('Arial', 12), width=10, height=1, command=self.parse_hit_click_1) self.button_1.pack(before=self.text1) """界说按钮2,绑定触收变乱办法""" self.button_2 = tk.Button(self.window, text='拂拭', font=('Arial', 12), width=10, height=1, command=self.parse_hit_click_2) self.button_2.pack(anchor="e") """界说富文本笔墨的显现""" self.start_url = 'https://travel.qunar.com/place/' self.headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36' } # 收收恳求,获得呼应,剖析呼应
- response = session.get(self.start_url, headers=self.headers).html
- # 提与一切目标天(都会)的url
- city_url_list = response.xpath(
- '//*[@id="js_destination_recommend"]/div[2]/div[1]/div[2]/dl/dd/div/ul/li/a/@href')
- city_id_list = [''.join(re.findall(r'-cs(.*?)-', i)) for i in city_url_list]
- # 提与一切的都会称号
- city_name_list = response.xpath(
- '//*[@id="js_destination_recommend"]/div[2]/div[1]/div[2]/dl/dd/div/ul/li/a/text()') self.dict_data = dict(zip(city_id_list, city_name_list)) text_info = '' for city_id, city_name in zip(city_id_list, city_name_list): text_info += city_id + ":" + city_name + '\t\t' self.text1.insert("insert", text_info) def parse_hit_click_1(self): """线程联系关系:界说触收变乱1, 将施行成果显现正在文本框中""" Thread(target=self.parse_start_url_job).start() def parse_city_id_name_info(self): """ 富文本内乱容展现: :return: """ # 收收恳求,获得呼应,剖析呼应
- response = session.get(self.start_url, headers=self.headers).html
- # 提与一切目标天(都会)的url
- city_url_list = response.xpath(
- '//*[@id="js_destination_recommend"]/div[2]/div[1]/div[2]/dl/dd/div/ul/li/a/@href')
- city_id_list = [''.join(re.findall(r'-cs(.*?)-', i)) for i in city_url_list]
- # 提与一切的都会称号
- city_name_list = response.xpath(
- '//*[@id="js_destination_recommend"]/div[2]/div[1]/div[2]/dl/dd/div/ul/li/a/text()') self.dict_data = dict(zip(city_id_list, city_name_list)) text_info = '' for city_id, city_name in zip(city_id_list, city_name_list): text_info += city_id + ":" + city_name + '\t\t****' self.text1.insert("insert", text_info) def parse_start_url_job(self): # 从输进窗心获得输进 city_id = self.entry_user.get() self.text1.delete("1.0", "end") # 非常捕捉,能否存正在key值 try: city_name = self.dict_data[city_id] self.parse_request_yj(city_id, city_name) except: # 报错提醒 msgbox.showerror(title='毛病', message='检测到瞎弄,请从头输进!') def parse_request_yj(self, city_id, city_name): """ 拼接纪行地点,停止翻页 :param city_id: 都会的id :param city_name: 都会的称号 :return: """ while self.is_running: yj_url = f'https://travel.qunar.com/place/api/html/books/dist/{city_id}?sortField=0&pageSize=10&page={self.start_page}' response = session.get(yj_url, headers=self.headers).json()['data'].replace('\\', '') html = etree.HTML(response) # 提与纪行的题目: title_list = html.xpath('//h3[@class="tit"]/a/text()') # 逝世轮回的停止前提 if not title_list: print("该都会曾经收罗到最初一页----------都会切换中---------logging!!!") break else: # 提与纪行做者 author_list = html.xpath('//span[@class="user_name"]/a/text()') # 动身工夫 date_list = html.xpath('//span[@class="date"]/text()') # 玩耍工夫 days_list = html.xpath('//span[@class="days"]/text()') # 浏览量 read_list = html.xpath('//span[@class="icon_view"]/span/text()') # 面赞量 like_count_list = html.xpath('//span[@class="icon_love"]/span/text()') # 批评量 icon_list = html.xpath('//span[@class="icon_comment"]/span/text()') # 纪行地点 text_url_list = html.xpath('//h3[@class="tit"]/a/@href') """机关保留数据格局字典""" for a, b, c, d, e, f, g, h in zip(title_list, author_list, date_list, days_list, read_list, like_count_list, icon_list, text_url_list): dict_dd = { city_name: [a, b, c, d, e, f, g, h] } self.text1.insert("insert", f"{a}-----------收罗完成!!!" + '\n') self.SaveExcels(dict_dd) self.start_page += 1 def SaveExcels(self, data): # 获得表的称号 sheet_name = [i for i in data.keys()][0] # 创立保留excel表格的文件夹 # os.getcwd() 获得当前文件途径 os_mkdir_path = os.getcwd() + '/数据/' # 判定那个途径能否存正在,没有存正在便创立 if not os.path.exists(os_mkdir_path): os.mkdir(os_mkdir_path) # 判定excel表格能否存正在 事情簿文件称号 os_excel_path = os_mkdir_path + '数据.xls' if not os.path.exists(os_excel_path): # 没有存正在,创立事情簿(也便是创立excel表格) workbook = xlwt.Workbook(encoding='utf-8') """事情簿中创立新的sheet表""" # 设置表名 worksheet1 = workbook.add_sheet(sheet_name, cell_overwrite_ok=True) """设置sheet表的表头""" sheet1_headers = ('纪行题目', '公布纪行的做者称号', '动身工夫', '玩耍工夫', '浏览量', '面赞量', '批评量', '纪行地点') # 将表头写进事情簿 for header_num in range(0, len(sheet1_headers)): # 设置表格少度 worksheet1.col(header_num).width = 2560 * 3 # 写进表头 止, 列, 内乱容 worksheet1.write(0, header_num, sheet1_headers[header_num]) # 轮回结束,代表表头写进完成,保留事情簿 workbook.save(os_excel_path) """=============================已有事情簿增加新表===============================================""" # 翻开事情薄 workbook = xlrd.open_workbook(os_excel_path) # 获得事情薄中一切表的称号 sheets_list = workbook.sheet_names() # 假如表称号:字典的key值没有正在事情簿的表名列表中 if sheet_name not in sheets_list: # 复造先有事情簿工具 work = copy(workbook) # 经由过程复造过去的事情簿工具,创立新表 -- 保留本有表构造 sh = work.add_sheet(sheet_name) # 给新表设置表头 excel_headers_tuple = ('纪行题目', '公布纪行的做者称号', '动身工夫', '玩耍工夫', '浏览量', '面赞量', '批评量', '纪行地点') for head_num in range(0, len(excel_headers_tuple)): sh.col(head_num).width = 2560 * 3 # 止,列, 内乱容, 款式 sh.write(0, head_num, excel_headers_tuple[head_num]) work.save(os_excel_path) """=========================================================================================""" # 判定事情簿能否存正在 if os.path.exists(os_excel_path): # 翻开事情簿 workbook = xlrd.open_workbook(os_excel_path) # 获得事情薄中一切表的个数 sheets = workbook.sheet_names() for i in range(len(sheets)): for name in data.keys(): worksheet = workbook.sheet_by_name(sheets[i]) # 获得事情薄中一切表中的表名取数据名比照 if worksheet.name == name: # 获得表中已存正在的止数 rows_old = worksheet.nrows # 将xlrd工具拷贝转化为xlwt工具 new_workbook = copy(workbook) # 获得转化后的事情薄中的第i张表 new_worksheet = new_workbook.get_sheet(i) for num in range(0, len(data[name])): new_worksheet.write(rows_old, num, data[name][num]) new_workbook.save(os_excel_path) def parse_hit_click_2(self): """界说触收变乱2,删除文本框中内乱容""" self.entry_user.delete(0, "end") # self.entry_passwd.delete(0, "end") self.text1.delete("1.0", "end") self.parse_city_id_name_info() def center(self): """创立窗心居中函数办法""" ws = self.window.winfo_screenwidth() hs = self.window.winfo_screenheight() x = int((ws / 2) - (800 / 2)) y = int((hs / 2) - (600 / 2)) self.window.geometry('{}x{}+{}+{}'.format(800, 600, x, y)) def run_loop(self): """抑制修正窗体巨细规格""" self.window.resizable(False, False) """窗心居中""" self.center() """窗心保持--耐久化""" self.window.mainloop()if __name__ == '__main__': t = TKSpider() t.run_loop()
复造代码 代码仅供进修!!
代码仅供进修!!
代码仅供进修!!
祝各人进修python顺遂!
免责声明:假如进犯了您的权益,请联络站少,我们会实时删除侵权内乱容,感谢协作! |
1、本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,按照目前互联网开放的原则,我们将在不通知作者的情况下,转载文章;如果原文明确注明“禁止转载”,我们一定不会转载。如果我们转载的文章不符合作者的版权声明或者作者不想让我们转载您的文章的话,请您发送邮箱:Cdnjson@163.com提供相关证明,我们将积极配合您!
2、本网站转载文章仅为传播更多信息之目的,凡在本网站出现的信息,均仅供参考。本网站将尽力确保所提供信息的准确性及可靠性,但不保证信息的正确性和完整性,且不对因信息的不正确或遗漏导致的任何损失或损害承担责任。
3、任何透过本网站网页而链接及得到的资讯、产品及服务,本网站概不负责,亦不负任何法律责任。
4、本网站所刊发、转载的文章,其版权均归原作者所有,如其他媒体、网站或个人从本网下载使用,请在转载有关文章时务必尊重该文章的著作权,保留本网注明的“稿件来源”,并自负版权等法律责任。
|