[英]extract data from website using python
我最近開始學習python,我做的第一個項目之一是從兒子教室的網頁上刪除更新,並向我發送有關更新站點的通知。 原來這是一個簡單的項目,所以我想對此進行擴展並創建一個腳本,該腳本將自動檢查我們的樂透號碼是否命中。 不幸的是,我一直無法弄清楚如何從網站上獲取數據。 這是我昨晚的嘗試之一。
from bs4 import BeautifulSoup
import urllib.request
webpage = "http://www.masslottery.com/games/lottery/large-winningnumbers.html"
websource = urllib.request.urlopen(webpage)
soup = BeautifulSoup(websource.read(), "html.parser")
span = soup.find("span", {"id": "winning_num_0"})
print (span)
Output is here...
<span id="winning_num_0"></span>
如果我使用Web瀏覽器“查看源代碼”,上面列出的輸出也是我看到的結果。 當我使用Web瀏覽器“檢查元素”時,我可以在“檢查元素”面板中看到中獎號碼。 不幸的是,我什至不確定網絡瀏覽器如何/在何處獲取數據。 是從另一個頁面加載還是在后台加載腳本? 我以為以下教程將對我有所幫助,但是我無法使用類似的命令來獲取數據。
任何幫助表示贊賞。 謝謝
如果您仔細查看頁面的源代碼(我剛剛使用curl
),則可以看到此塊
<script type="text/javascript">
// <![CDATA[
var dataPath = '../../';
var json_filename = 'data/json/games/lottery/recent.json';
var games = new Array();
var sessions = new Array();
// ]]>
</script>
那recent.json
像拇指一樣伸出來(我一開始實際上錯過了dataPath
部分)。
經過嘗試后,我想到了這個:
curl http://www.masslottery.com/data/json/games/lottery/recent.json
正如lari在評論中指出的那樣,這比抓取HTML更容易。 這很容易,實際上:
import json
import urllib.request
from pprint import pprint
websource = urllib.request.urlopen('http://www.masslottery.com/data/json/games/lottery/recent.json')
data = json.loads(websource.read().decode())
pprint(data)
data
現在是字典,您可以使用它來做任何類似字典的事情。 還有祝你好運 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.