首页 > 解决方案 > 如何从带有子框架的网站中抓取信息

问题描述

我正在尝试构建一个简单的网络爬虫来从学生宇宙中提取航班信息。

我使用 selenium 浏览网页以获取我想要的位置和日期的航班信息。我可以毫无问题地访问包含所有信息的正确页面。但是,我很难从网页中提取信息。我使用 xpath 来定位那些包含所需信息的元素,但提取信息是不成功的,除非我手动上下滚动网页。这似乎与网站中嵌入的子框架有关。我尝试迭代所有 iframe 以查看是否使用命令 driver.switch_to.frame() 获取信息,但问题仍然存在。

如果有人能就如何从此类网站上抓取信息提供一些帮助,那就太好了。该问题可能不是由子帧的存在引起的。任何意见表示赞赏。我用来提取航班信息的代码如下所示,文章标签包含所有信息(承运人名称、出发时间、到达时间等)。我首先要做的是找到这个元素。

    def parseprice(driver):
        driver.maximize_window()
        parser = lxml.html.fromstring(driver.page_source,driver.current_url)
        flights=parser.xpath('//article[@class="itin activeCheck"]') 
        driver.quit()
        carriername=flights[0].xpath('//p[@id="airlineName0"]/text()')
        duration=flights[0].xpath('//strong[@id="duration0"]/text()')
        depttime=flights[0].xpath('//span[@id="departureTime0"]/text()')
        arrtime=flights[0].xpath('//span[@id="arrivalTime0"]/text()')
        price=flights[0].xpath('//p[@ng-click="pricePoint()"]//text()')
        stops=flights[0].xpath('//p[@id="stops0"]//text()')
        stoplis=list()
        for st in stops:
            res1=re.search('^(\d)+\D*',st)
            if res1 is not None:
                stoplis.append(int(res1.group(1)))
        now=datetime.datetime.now()
        now=now.timetuple()
        for i in range(20):
        yield{'current time':str(now[1])+'/'+str(now[2])+'/'+str(now[0]),'carrier':carriername[i],'duration':duration[i],'price':price[i],'numstops':stoplis[i],'departure_time':depttime[i],'arrival_time':arrtime[i]}

标签: pythonscreen-scraping

解决方案


推荐阅读