首先下载selenium模块,pip install selenium,下载一个浏览器驱动程序(我这里使用谷歌)。
#需要用到的所有包
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from lxml import etree
首先实现登陆去哪儿网,这部分没什么难点,需要注意的是一个滑块验证
我们可以定位小滑块和滑动轨道,通过location和size方法获取他们位置和宽度高度,用法如下
huakuai = browser.find_element(By.XPATH, '//*[@id="app"]/div/div[2]/div/div[1]/div[3]/div/div[5]/div/div/div[3]/div[3]')
huakuai_left_right = huakuai.location
huakuai_height_widtht = huakuai.size
# print(huakuai_left_right,huakuai_height_widtht)
guidao = browser.find_element(By.XPATH, '//*[@id="app"]/div/div[2]/div/div[1]/div[3]/div/div[5]/div/div/div[3]/div[2]')
guidao_left_rihgt = guidao.location
guigao_height_widtht = guidao.size
# print(guidao_left_rihgt,guigao_height_widtht)
length = guigao_height_widtht['width'] - huakuai_height_widtht['width']
以字典形式返回
#需要滑行的长度就可以算出来(实际长度需要加上左右边框各1)
length=guigao_height_widtht['width']-huakuai_height_widtht['width']
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from lxml import etree
aa = input('出发地址:')
bb = input('目的地:')
cc = input('出发日期(注意格式例如 2022-03-28):')
# 无头浏览器
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_argument('--headless')
option.add_argument('--disable-gpu')
s = Service("chromedriver.exe")
browser = webdriver.Chrome(service=s, options=option)
# browser = webdriver.Chrome(service=s)
# 规避检测
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})
br

本文介绍了使用Python的Selenium模块进行模拟登录去哪儿网并爬取火车票数据的过程。首先,详细讲解了如何下载Selenium及配置浏览器驱动。在登录环节,提到了滑块验证的处理方法,通过定位滑块和轨道来实现。接着,描述了如何选择出发地、目的地,修改默认日期,并利用Selenium的键盘事件。最后,展示了如何抓取车次、出发时间和运行时间等信息,强调了对页面元素的选择和遍历技巧。

最低0.47元/天 解锁文章
1179

被折叠的 条评论
为什么被折叠?



