到目前为止,我们有一个函数来加载更多的结果,还有一个函数来抓取这些结果。我可以在这里结束这篇文章,您仍然可以手动使用这些工具,并在您自己浏览的页面上使用抓取功能,但我确实提到了一些关于向您自己发送电子邮件和其他信息的内容!这都在下一个功能里面。

它要求你填写城市和日期。从那里,它将打开kayak字符串中的地址,该字符串直接进入“最佳”结果页排序。在第一次刮取之后,我顺利地得到了价格最高的矩阵。它将用于计算平均值和最小值,与Kayak的预测一起在电子邮件中发送(在页面中,它应该在左上角)。这是在单一日期搜索中可能导致错误的原因之一,因为那里没有矩阵元素。

def start_kayak(city_from, city_to, date_start, date_end):

"""City codes - it's the IATA codes!

Date format - YYYY-MM-DD"""

kayak = ('https://www.kayak.com/flights/' + city_from + '-' + city_to +

'/' + date_start + '-flexible/' + date_end + '-flexible?sort=bestflight_a')

driver.get(kayak)

sleep(randint(8,10))

# sometimes a popup shows up, so we can use a try statement to check it and close

try:

xp_popup_close = '//button[contains(@id,"dialog-close") and contains(@class,"Button-No-Standard-Style close ")]'

driver.find_elements_by_xpath(xp_popup_close)[5].click()

except Exception as e:

pass

sleep(randint(60,95))

print('loading more.....')

# load_more()

print('starting first scrape.....')

df_flights_best = page_scrape()

df_flights_best['sort'] = 'best'

sleep(randint(60,80))

# Let's also get the lowest prices from the matrix on top

matrix = driver.find_elements_by_xpath('//*[contains(@id,"FlexMatrixCell")]')

matrix_prices = [price.text.replace('$','') for price in matrix]

matrix_prices = list(map(int, matrix_prices))

matrix_min = min(matrix_prices)

matrix_avg = sum(matrix_prices)/len(matrix_prices)

print('switching to cheapest results.....')

cheap_results = '//a[@data-code = "price"]'

driver.find_element_by_xpath(cheap_results).click()

sleep(randint(60,90))

print('loading more.....')

# load_more()

print('starting second scrape.....')

df_flights_cheap = page_scrape()

df_flights_cheap['sort'] = 'cheap'

sleep(randint(60,80))

print('switching to quickest results.....')

quick_results = '//a[@data-code = "duration"]'

driver.find_element_by_xpath(quick_results).click()

sleep(randint(60,90))

print('loading more.....')

# load_more()

print('starting third scrape.....')

df_flights_fast = page_scrape()

df_flights_fast['sort'] = 'fast'

sleep(randint(60,80))

# saving a new dataframe as an excel file. the name is custom made to your cities and dates

final_df = df_flights_cheap.append(df_flights_best).append(df_flights_fast)

final_df.to_excel('search_backups//{}_flights_{}-{}_from_{}_to_{}.xlsx'.format(strftime("%Y%m%d-%H%M"),

city_from, city_to,

date_start, date_end), index=False)

print('saved df.....')

# We can keep track of what they predict and how it actually turns out!

xp_loading = '//div[contains(@id,"advice")]'

loading = driver.find_element_by_xpath(xp_loading).text

xp_prediction = '//span[@class="info-text"]'

prediction = driver.find_element_by_xpath(xp_prediction).text

print(loading+'\n'+prediction)

# sometimes we get this string in the loading variable, which will conflict with the email we send later

# just change it to "Not Sure" if it happens

weird = '¯\\_(ツ)_/¯'

if loading == weird:

loading = 'Not sure'

username = 'YOUREMAIL@hotmail.com'

password = 'YOUR PASSWORD'

server = smtplib.SMTP('smtp.outlook.com', 587)

server.ehlo()

server.starttls()

server.login(username, password)

msg = ('Subject: Flight Scraper\n\n\

Cheapest Flight: {}\nAverage Price: {}\n\nRecommendation: {}\n\nEnd of message'.format(matrix_min, matrix_avg, (loading+'\n'+prediction)))

message = MIMEMultipart()

message['From'] = 'YOUREMAIL@hotmail.com'

message['to'] = 'YOUROTHEREMAIL@domain.com'

server.sendmail('YOUREMAIL@hotmail.com', 'YOUROTHEREMAIL@domain.com', msg)

print('sent email.....')

我使用Outlook帐户(hotmail.com)测试了这一点。虽然我没有使用Gmail帐户来测试它来发送电子邮件,但是您可以搜索许多替代方法,我前面提到的那本书也有其他的方法来实现这一点。如果您已经有一个Hotmail帐户,那么您替换您的详细信息,它应该可以工作。

如果您想探索脚本的某些部分正在做什么,请复制它并在函数之外使用它。只有这样你才能完全理解。

利用我们刚刚创造的一切

在所有这些之后,我们还可以想出一个简单的循环来开始使用我们刚刚创建的函数并使它们保持忙碌。完成四个“花式”提示,让你实际写下城市和日期(输入)。因为当我们进行测试时,我们不希望每次都输入这些变量,在需要的时候用下面的显式方法替换它。

city_from = input('From which city? ')

city_to = input('Where to? ')

date_start = input('Search around which departure date? Please use YYYY-MM-DD format only ')

date_end = input('Return when? Please use YYYY-MM-DD format only ')

# city_from = 'LIS'

# city_to = 'SIN'

# date_start = '2019-08-21'

# date_end = '2019-09-07'

for n in range(0,5):

start_kayak(city_from, city_to, date_start, date_end)

print('iteration {} was complete @ {}'.format(n, strftime("%Y%m%d-%H%M")))

# Wait 4 hours

sleep(60*60*4)

print('sleep finished.....')

如果你做到了这一步,恭喜你!我能想到的改进有很多,比如与Twilio集成,向您发送文本消息而不是电子邮件。您还可以使用VPN或更模糊的方法同时从多个服务器上研究搜索结果。有验证码的问题,可能会不时出现,但有解决这类问题的方法。我认为您在这里有一些非常可靠的基础,我鼓励您尝试添加一些额外的特性。也许您希望Excel文件作为附件发送。我总是欢迎建设性的反馈,所以请随时在下面发表评论。我试着回应每一个人!

使用脚本的测试运行示例

如果您想了解更多关于web抓取的知识,我强烈推荐您使用python进行web抓取。我真的很喜欢这些例子和对代码如何工作的清晰解释。如果你更喜欢社交媒体的抓取,还有一本关于这个主题的好书,以后有机会在这里介绍给你们~

python抓取_如何用Python抓取最便宜的机票信息(下)相关推荐

  1. python md5加密_如何用python“优雅”的调用有道翻译?

    前言 其实在以前就盯上有道翻译了的,但是由于时间问题一直没有研究(我的骚操作还在后面,记得关注),本文主要讲解如何用python调用有道翻译,讲解这个爬虫与有道翻译的js"斗争"的 ...

  2. python小助手_如何用python写个人专属群聊提醒小助手?

    前言 大家还记得教会父母玩微信是什么时候吗?父母学会后,我们的生活就发生了「质」的变化,父母也许会吐槽你的微信头像不好,要你换一个头像. 最近 pk哥 又被母后大人吐槽了,原因是亲戚微信群里某个亲戚生 ...

  3. python预测房价走势_如何用 Python 预测房价走势?

    原标题:如何用 Python 预测房价走势? 买房应该是大多数都会要面临的一个选择,当前经济和政策背景下,未来房价会涨还是跌?这是很多人都关心的一个话题.今天分享的这篇文章,以波士顿的房地产市场为例, ...

  4. python三维柱形图_如何用Python绘制3D柱形图

    本文主要讲解如何使用python绘制三维的柱形图,如下图 源代码如下: import numpy as np import matplotlib.pyplot as plt from mpl_tool ...

  5. 用python画耳朵_如何用python画一只兔子

    python的用处真的是太广泛了,今天在网上学习查找资料时,看到有网友用python来画画.用python画出一只兔子,为大家分享一下:如何用python画一只兔子? 画了一只大耳朵小兔子,灵感来源是 ...

  6. 用python画小兔子_如何用Python画一只兔子——turtle库circle()画圆函数的详细用法介绍...

    周末学习了一下turtle库的基本函数,试着画了一只大耳朵小兔子,灵感来源是jellycat邦尼兔.turtle库中circle()函数用来画弧,但和通常先确定原点,再根据半径.夹角画弧的方法有所不同 ...

  7. 用python画耳朵_如何用python画猪头

    用python画猪头的方法:首先设置画布和画笔,代码为[a.screensize(400,300)a.setup(width=400,height=300)]:然后画脸型,代码为[.goto(-100 ...

  8. python怎么读_如何用Python读写文件

    前面我们已经介绍了很多Python相关的基础知识,大家是不是对Python已经有了进一步认识了呢?作为人工智能时代的热门编程语言,开始接触并学习Python的孩子越来越多,家长们都不想让自己的孩子落于 ...

  9. python旅游推荐系统_如何用Python搭建一个简单的推荐系统?

    推荐系统的相关知识我们已在前文中提到,在这篇文章中,我们会介绍如何用Python来搭建一个简单的推荐系统. 本文使用的数据集是MovieLens数据集,该数据集由明尼苏达大学的Grouplens研究小 ...

  10. 用python开启相机_如何用Python打开realsenseD435相机并获取相机参数

    如何用Python打开realsenseD435相机 import pyrealsense2 as rs import numpy as np import cv2 if __name__ == &q ...

最新文章

  1. python网络爬虫权威指南 百度云-分析《Python网络爬虫权威指南第2版》PDF及代码...
  2. Scala集合常用方法:reduceLeft/reduceRight
  3. Redis Monitor命令 - 实时打印出Redis服务器接收到的命令,调试用
  4. MSF(二):msf外部/内部常用命令
  5. c语言素数程序出现大空行,C语言实现寻找大素数
  6. springboot data.redis.RedisConnectionFactory 集成问题
  7. 丘成桐:年轻学者要敢于“无法无天”
  8. golang CI: Use result of type assertion to simplify cases SCC-S1034
  9. java 获取本机mac地址并转为字符串
  10. mysql 楼层_MySQL 8.0.0 发布!
  11. pku1833 排列(use next_permutation)
  12. 计算机电缆国家标准是什么,计算机电缆执行标准是什么
  13. Android Hook技术的简单实现
  14. 【论文笔记】 Leverage Lexical Knowledge Base for Chinese NER via Collborative Graph Network
  15. 面试笔记-1.计算机网络面试核心
  16. docker磁盘清理
  17. C#(三十二)之Windows绘图
  18. 多方协同,华为云IoT ,加速批量交付
  19. 系统认证风险预测方案总结
  20. 数据库为啥查询那么慢?

热门文章

  1. AMD推出用于工作站PC的64核心Threadripper Pro
  2. 用Python绘制多彩的斐波那契螺旋线(黄金螺旋线)
  3. 【eclipse】注释模版
  4. 【TO B 乱谈】这次我们不割韭菜,只谈区块链
  5. uniApp生成Excel,uniApp导出Excel,微信小程序生成Excel,微信小程序导出Excel
  6. 还在为怎么写SCI投稿邮件发愁?给你收集7个阶段邮件模板
  7. 无线网络在校园网中的应用
  8. 肖寒20181209
  9. 借用图文智能排版制作精美的锁屏图片
  10. python challenge 7-12关 攻略