[英]Extracting data from Web
一個真正的新手問題。 我正在為我的家庭使用一個小的 python 腳本,它將收集特定機票的數據。
我想從 Skyscanner 中提取數據(使用 BeautifulSoap 和 urllib)。 例子:
我對存儲在這種元素中的所有數據感興趣,特別是價格: http : //shrani.si/f/1w/An/1caIzEzT/capture.png
因為它們不在 HTML 中,我可以提取它們嗎?
我認為問題在於這些值是通過瀏覽器運行的 javascript 代碼呈現的,而urllib
則沒有 - 您應該使用可以執行 javascript 代碼的庫。
我只是在谷歌上搜索了crawler python javascript
,我得到了一些建議使用selenium或webkit 的stackoverflow 問題和答案。 您可以通過scrapy使用這些庫。 這里有兩個片段:
我一直在研究同樣的問題。 我被介紹給 Beautifulsoup,后來我了解了 Scrapy。 Beautifulsoup 非常易於使用,特別是如果您是新手。 Scrapy 顯然具有更多“功能”,但我相信您可以使用 Beautifulsoup 來滿足您的需求。
我遇到了同樣的問題,無法訪問通過 Javascript 加載信息的網站,幸好 Selenium 是救世主。
可以在此處找到有關 Selenium 的精彩介紹。
安裝: 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
您甚至不需要 BeautifulSoup 來提取數據。
只需執行此操作,您的響應就會轉換為非常易於處理的字典。
text = json.loads("你的主要響應內容的文本")
您現在可以打印字典中的任何鍵值對。 試試看。 這非常容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.