selenium+python初见入门

selenium是一款浏览器自动化框架,也算是一种web爬虫,不同于类似requests的爬虫,selenium模拟人工打开浏览器进行操作。支持java,python,.net

它首先需要driver来驱动你电脑上安装的浏览器,例如chrome需要下载chromedriver:https://sites.google.com/a/chromium.org/chromedriver/downloads(需要科学上网)

其他浏览器的driver:

Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox: https://github.com/mozilla/geckodriver/releases
Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

首先创建driver对象

from selenium import webdriver

one = webdriver.Chrome()
one.get('http://flights.ctrip.com/international/search/oneway-nkg-tyo?depdate=2018-10-7&cabin=y_s&adult=1')

  这里已经将chromedriver设为PATH,如果不这么做可以

one = webdriver.Chrome(executable_path="./drivers/chromedriver.exe")

指向driver的路径

get()方法打开浏览器并打开指定页面,这样浏览器就自动出现在你的屏幕上了,接下来继续执行代码

在本例子中我在携程搜索南京到东京的飞机票

我想查找最低票价可以点击价格这个按钮

打开f12源码查找

可见class名字sort-item ticket-price,selenium提供了几种查找元素的方法:

find_element_by_id

find_element_by_name

find_element_by_xpath

find_element_by_link_text

find_element_by_partial_link_text

find_element_by_tag_name

find_element_by_class_name

find_element_by_css_selector

也可以查找多个元素 只要在上面element改成elements即可,

这里的class是复合型的,需要用css选择器查找

pricedown = one.find_element_by_css_selector(".sort-item.ticket-price")

然后模拟操作点击

pricedown.click()

页面开始按价格递增排序

观察html5源码,飞机信息都在flightitem中

于是将其遍历出来,并将其中信息一并提取

for aflight in flightinfo:
    flightno=aflight.find_element_by_class_name("plane-No")
    atime=aflight.find_element_by_class_name("time")
    consume=aflight.find_element_by_class_name("flight-consume")
    pricefa=aflight.find_element_by_class_name("price-box")
    price=pricefa.find_element_by_tag_name("div")
    print(flightno.text+atime.text+consume.text+price.text)

这样就能看最低机票了(没卵用

猜你喜欢

转载自www.cnblogs.com/batt1ebear/p/9747206.html