[英]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.