我正试图从航班搜索页面抓取一些数据.

此页面以这种方式工作:

你填写一个表格,然后你点击按钮搜索 – 这没关系.当您单击该按钮时,您将被重定向到包含结果的页面,这就是问题所在.这个页面连续添加结果,例如一分钟,这不是什么大问题 – 问题是得到所有这些结果.当您使用真正的浏览器时,您必须向下滚动页面并显示这些结果.所以我试图使用Selenium向下滚动.它可能在页面底部向下滚动可能非常快,或者是跳转而不是滚动页面不会加载任何新结果.

当你慢慢向下滚动时,它会重新加载结果,但是如果你这么做就会停止加载.

我不确定我的代码是否有助于理解,所以我附上它.

SEARCH_STRING = """URL"""

class spider():

    def __init__(self):
self.driver = webdriver.Firefox() @staticmethod
def prepare_get(dep_airport,arr_airport,dep_date,arr_date):
string = SEARCH_STRING%(dep_airport,arr_airport,arr_airport,dep_airport,dep_date,arr_date)
return string def find_flights_html(self,dep_airport, arr_airport, dep_date, arr_date):
if isinstance(dep_airport, list):
airports_string = str(r'%20').join(dep_airport)
dep_airport = airports_string wait = WebDriverWait(self.driver, 60) # wait for results
self.driver.get(spider.prepare_get(dep_airport, arr_airport, dep_date, arr_date))
wait.until(EC.invisibility_of_element_located((By.XPATH, '//img[contains(@src, "loading")]')))
wait.until(EC.invisibility_of_element_located((By.XPATH, u'//div[. = "Poprosíme o trpezlivosť, hľadáme pre Vás ešte viac letov"]/preceding-sibling::img')))
self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight);") self.driver.find_element_by_xpath('//body').send_keys(Keys.CONTROL+Keys.END)
return self.driver.page_source @staticmethod
def get_info_from_borderbox(div):
arrival = div.find('div',class_='departure').text
price = div.find('div',class_='pricebox').find('div',class_=re.compile('price'))
departure = div.find_all('div',class_='departure')[1].contents
date_departure = departure[1].text
airport_departure = departure[5].text
arrival = div.find_all('div', class_= 'arrival')[0].contents
date_arrival = arrival[1].text
airport_arrival = arrival[3].text[1:]
print 'DEPARTURE: '
print date_departure,airport_departure
print 'ARRIVAL: '
print date_arrival,airport_arrival @staticmethod
def get_flights_from_result_page(html): def match_tag(tag, classes):
return (tag.name == 'div'
and 'class' in tag.attrs
and all([c in tag['class'] for c in classes])) soup = mLib.getSoup_html(html)
divs = soup.find_all(lambda t: match_tag(t, ['borderbox', 'flightbox', 'p2'])) for div in divs:
spider.get_info_from_borderbox(div) print len(divs) spider_inst = spider() print spider.get_flights_from_result_page(spider_inst.find_flights_html(['BTS','BRU','PAR'], 'MAD', '2015-07-15', '2015-08-15'))

因此,我认为主要问题是滚动太快而无法触发新的结果加载.

你知道如何使它工作吗?

最佳答案
这是一个不同的方法,对我有用,包括滚动到最后一个搜索结果的视图,并等待再次滚动之前加载其他元素:

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC class wait_for_more_than_n_elements(object):
def __init__(self, locator, count):
self.locator = locator
self.count = count def __call__(self, driver):
try:
count = len(EC._find_elements(driver, self.locator))
return count >= self.count
except StaleElementReferenceException:
return False driver = webdriver.Firefox() dep_airport = ['BTS', 'BRU', 'PAR']
arr_airport = 'MAD'
dep_date = '2015-07-15'
arr_date = '2015-08-15' airports_string = str(r'%20').join(dep_airport)
dep_airport = airports_string url = "https://www.pelikan.sk/sk/flights/list?dfc=C%s&dtc=C%s&rfc=C%s&rtc=C%s&dd=%s&rd=%s&px=1000&ns=0&prc=&rng=1&rbd=0&ct=0" % (dep_airport, arr_airport, arr_airport, dep_airport, dep_date, arr_date)
driver.maximize_window()
driver.get(url) wait = WebDriverWait(driver, 60)
wait.until(EC.invisibility_of_element_located((By.XPATH, '//img[contains(@src, "loading")]')))
wait.until(EC.invisibility_of_element_located((By.XPATH,
u'//div[. = "Poprosíme o trpezlivosť, hľadáme pre Vás ešte viac letov"]/preceding-sibling::img'))) while True: # TODO: make the endless loop end
results = driver.find_elements_by_css_selector("div.flightbox")
print "Results count: %d" % len(results) # scroll to the last element
driver.execute_script("arguments[0].scrollIntoView();", results[-1]) # wait for more results to load
wait.until(wait_for_more_than_n_elements((By.CSS_SELECTOR, 'div.flightbox'), len(results)))

笔记:

>你需要弄清楚何时停止循环 – 例如,在特定的len(结果)值
> wait_for_more_than_n_elements是一个custom Expected Condition,它有助于确定何时加载下一部分,我们可以再次滚动

转自: https://www.cnblogs.com/yipianshuying/p/10040461.html

使用Selenium慢慢向下滚动页面的更多相关文章

  1. 向下滚动页面加载图片的js

    js代码 scroll.photo.js : window.imgscroll = { options: { target: null, //插入图片的目标位置 img_list: null, //图 ...

  2. 利用python+selenium在pycharm下进行页面登陆的半自动测试

    很久没有写了,现在正式入职,准备好好干,加油! 我的第一个较正式的测试代码: from selenium import webdriverimport unittestimport sysimport ...

  3. selenium从入门到应用 - 5,页面对象设计模式下的页面模块

    本系列所有代码 https://github.com/zhangting85/simpleWebtest 本文将介绍一个Java+TestNG+Maven+Selenium的web自动化测试脚本环境下 ...

  4. hexo next 主题 : 实现点击跳转到文章的时候文章的页面自动实现滚轮效果,向下滚动到阅读的位置。

    个人博客:https://mmmmmm.me 源码:https://github.com/dataiyangu/dataiyangu.github.io 背景: 博主的博客希望实现能够在点击到某个文章 ...

  5. js-scroll判断页面是向上滚动还是向下滚动

    原理:那当前的scrollTop和之前的scrollTop对比 如果变大了,表示向下滚动(scrollTop值变大): 如果变小了,表示向上滚动(scrollTop值变小). 方法一:js代码: $( ...

  6. js 页面向下滚动

    向下滚动一段距离 距离顶部距离 var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; <scrip ...

  7. 抓取Js动态生成数据且以滚动页面方式分页的网页

    代码也可以从我的开源项目HtmlExtractor中获取. 当我们在进行数据抓取的时候,如果目标网站是以Js的方式动态生成数据且以滚动页面的方式进行分页,那么我们该如何抓取呢? 如类似今日头条这样的网 ...

  8. 向上滚动或者向下滚动分页异步加载数据(Ajax + lazyload)[上拉加载组件]

    /**** desc : 分页异步获取列表数据,页面向上滚动时候加载前面页码,向下滚动时加载后面页码 ajaxdata_url ajax异步的URL 如data.php page_val_name a ...

  9. jQuery带控制按钮向上和向下滚动文本列表

    效果:http://hovertree.com/texiao/jquery/64/ 效果图如下: 代码如下: <!DOCTYPE html> <html> <head&g ...

随机推荐

  1. 排查在 Azure 中新建 Windows 虚拟机时遇到的经典部署问题

    尝试创建新的 Azure 虚拟机 (VM) 时,遇到的常见错误是预配失败或分配失败. 当由于准备步骤不当,或者在从门户捕获映像期间选择了错误的设置而导致 OS 映像无法加载时,将发生预配失败. 当群集 ...

  2. VS :不会命中断点 代码版本与原始版本不同

    设置了断点,但是无法中断,提示"不会命中断点 代码版本与原始版本不同".这种情况下一般是生成的bin\debug下面的文件与实际代码不符. 但是这次确实没有问题,重新更新程序,清理 ...

  3. Mysql常用语句与函数(待续)

    -- 查询语句select class from stu_info where sid=1000000102;select * from stu_info t where t.age=88; -- t ...

  4. Asp.Net MVC源码调试

    首先下载MVC源代码,下载地址为:https://aspnetwebstack.codeplex.com/ 打开项目,卸载test文件夹下的所有项目和System.Web.WebPages.Admin ...

  5. CentOS 7 安装Rabbitmq

    第一步也是往往最重要的一步:下载安装包! Rabbitmq地址:https://github.com/rabbitmq/rabbitmq-server/releases/tag/v3.7.5 Erla ...

  6. 一个简单的php分页逻辑

    php分页 <?php include 'backend/conn.php'; $html = '<ul>'; //输出的html $pageDataNum=3; //每页显示10行 ...

  7. .NET正则表达式Regex

    一.IsMatch(Input,patter[,options]) 否则匹配 如果表达式在字符串中匹配,返回布尔值. if (Regex.IsMatch("a.b.c.d", @& ...

  8. 021.9 IO流 流总结

    ###################################################################################IO流的规律总结:解决的问题,开发 ...

  9. LVS.md

    LVS 概述 简介 LVS是Linux Virtual Server的简称,也就是Linux虚拟服务器, 是一个由章文嵩博士发起的自由软件项目,官方站点.现在LVS已经是 Linux标准内核的一部分, ...

  10. [TJOI2013]攻击装置

    题目 癌我竟然会做 发现我们要求的是一个最大独立集问题 发现一个格子和能攻击到的格子的奇偶性和它都不同,于是我们就可以按照\(i+j\)的奇偶性把整张图分成两个部分 两个部分之间没有连边 于是二分图最 ...