Tway Air 航班信息抓取:Python 代码实现
import requests
from lxml import etree
url = 'https://www.twayair.com/app/booking/layerAvailabilityList'
payload = '_csrf=986fbc1b-b37e-4b7b-8cad-586ed960e850&pos=KR¤cy=KRW'
headers = {
'Accept': 'text/html, */*; q=0.01',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie':
'HMF_CI=a09ef93ce8b8bf6611ff00ffc3446a0d09b3b0bfe621a6a879c954055a4f723381a2b29023785d8538c08a1035dbe098bfa190d376a6af4e7cc02e29b3ca470563;' \
' SESSION=3cb615cc-9f0a-4f1b-b9b8-433d36d72e36;' \
,
'Origin': 'https://www.twayair.com',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
'sec-ch-ua': ''Google Chrome';v='111', 'Not(A:Brand';v='8', 'Chromium';v='111'',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': ''Windows''
}
response = requests.request('POST', url, headers=headers, data=payload)
# print(response.text)
html=etree.HTML(response.text)
lis=html.xpath('//*[@id='price_list_route_1']/ul/li')
for li in lis[1:]:
# 出发城市
start_cityName=li.xpath('./a/div/div[1]/div[2]/span[1]/text()')[0]
# 出发时间
start_time = li.xpath('./a/div/div[1]/div[2]/strong/text()')[0].strip()
# 到达城市
reach_cityName=li.xpath('./a/div/div[1]/div[4]/span/text()')[0]
# 到达时间
reach_time=li.xpath('./a/div/div[1]/div[4]/strong/text()')[0].strip()
# 飞机名称
plan_name=li.xpath('./a/div/div[1]/div[1]/button[1]/text()')[0]
# 飞机航班号
plan_flightNumber=li.xpath('./a/div/div[1]/div[1]/button[2]/text()')[0]
# 飞机用时
plan_userTime=str(li.xpath('./a/div/div[1]/div[3]/p[1]/text()')[0]).replace(' ','')
# 飞机货币单位
plan_moneyUnit=li.xpath('./a/div/div[2]/span/text()')[0]
# 飞机价格
plan_price=li.xpath('./a/div/div[2]/strong/text()')[0]
# 飞机票数
plan_ticketNumber=li.xpath('./a/div/div[2]/p/text()')[0]
print(start_cityName,start_time,
reach_cityName,reach_time,
plan_name,plan_flightNumber,plan_userTime)
# 这里的时间为什么有空格,它有两段空格内容:可能是因为网页源代码中的时间文本中本身就含有空格,或者是网站为了使时间文本显示更美观而添加了额外的空格。无论是哪种情况,我们在提取数据时可以使用字符串的strip()方法将文本中的空格去除。比如,可以将代码中的以下两行:
start_time = li.xpath('./a/div/div[1]/div[2]/strong/text()')[0]
reach_time=li.xpath('./a/div/div[1]/div[4]/strong/text()')[0]
修改为:
start_time = li.xpath('./a/div/div[1]/div[2]/strong/text()')[0].strip()
reach_time=li.xpath('./a/div/div[1]/div[4]/strong/text()')[0].strip()
这样就可以将时间文本中的空格去除了。
本文介绍了使用 Python 的 requests 和 lxml 库抓取 Tway Air 网站的航班信息,并展示了如何去除时间文本中的空格。希望对您有所帮助。
注意: 该代码仅供学习参考,请勿用于非法用途。
原文地址: https://www.cveoy.top/t/topic/mw8K 著作权归作者所有。请勿转载和采集!