从Web提取数据

时间:2012-09-08 17:19:13

标签: python web-scraping beautifulsoup collect

一个真正的新手问题。 我正在为我的家庭使用一个小的python脚本,它将收集特定机票的数据。

我想从skyscanner中提取数据(使用BeautifulSoap和urllib)。例如:

http://www.skyscanner.net/flights/lond/rome/120922/120929/airfares-from-london-to-rome-in-september-2012.html

我对存储在这种元素中的所有数据感兴趣,特别是价格:http://shrani.si/f/1w/An/1caIzEzT/capture.png

因为它们不在HTML中,我可以提取它们吗?

3 个答案:

答案 0 :(得分:3)

我认为问题是这些值是通过浏览器运行的javascript代码呈现的,urllib没有 - 您应该使用可以执行javascript代码的库。

我只是用Google搜索crawler python javascript,我得到了一些stackoverflow问题和答案,建议使用seleniumwebkit。您可以通过scrapy使用这些库。这是两个片段:

Rendered/interactive javascript with gtk/webkit/jswebkit

Rendered Javascript Crawler With Scrapy and Selenium RC

答案 1 :(得分:1)

我一直在研究同样的问题。我被介绍到Beautifulsoup,后来才了解到Scrapy。 Beautifulsoup非常容易使用,特别是如果你是新手。 Scrapy显然有更多的“功能”,但我相信你可以通过Beautifulsoup来满足你的需求。

我遇到了无法访问通过Javascript加载信息的网站的相同问题,谢天谢地,Selenium是救世主。

可以找到对Selenium的精彩介绍here

安装:pip install selenium

下面是我放在一起的简单课程。您可以将其另存为.py文件并将其导入项目中。如果您调用方法retrieve_source_code(self, domain)并发送您尝试解析的超链接,则会返回完整页面的源代码,然后您可以将其放入Beautifulsoup并找到您要查找的信息!

例如:

airfare_url = 'http://www.skyscanner.net/flights/lond/rome/120922/120929/airfares-from-london-to-rome-in-september-2012.html'

soup = BeautifulSoup(SeleniumWebScraper.retrieve_source_code(airfare_url))

现在,您可以像使用Beautifulsoup一样解析soup

我希望能帮到你!

from selenium import webdriver
import requests

class SeleniumWebScraper():

    def __init__(self):
        self.source_code = ''
        self.is_page_loaded = 0
        self.driver = webdriver.Firefox()
        self.is_browser_closed = 0
        # To ensure the page has fully loaded we will 'implicitly' wait 
        self.driver.implicitly_wait(10)  # Seconds

    def close(self):
        self.driver.close()
        self.clear_source_code()
        self.is_page_loaded = 0
        self.is_browser_closed = 1

    def clear_source_code(self):
        self.source_code = ''
        self.is_page_loaded = 0

    def retrieve_source_code(self, domain):
        if self.is_browser_closed:
            self.driver = webdriver.Firefox()
        # The driver.get method will navigate to a page given by the URL.
        #  WebDriver will wait until the page has fully loaded (that is, the "onload" event has fired)
        #  before returning control to your test or script.
        # It's worth nothing that if your page uses a lot of AJAX on load then
        #  WebDriver may not know when it has completely loaded.
        self.driver.get(domain)

        self.is_page_loaded = 1
        self.source_code = self.driver.page_source
        return self.source_code

答案 2 :(得分:0)

您甚至不需要BeautifulSoup来提取数据。

只需执行此操作,您的响应就会转换为易于处理的字典。

text = json.loads(“您的主要响应内容为文本”)

您现在可以从字典中打印任何键值对。 试试看。超级容易。