從 Google news上爬top體育新聞
:)
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>今天體育</title> | |
<!--Boostrap4--> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> | |
<!-- JQuery --> | |
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> | |
<style> | |
p{ | |
font-size: 20px; | |
padding: 10px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="row"> | |
<div class="col-4"></div> | |
<div class="col-4"> | |
<h2>今日體育新聞</h2> | |
<p>顯示<input id="input"/>筆新聞</p> | |
<button type="button" class="btn btn-info" id='load'>搜尋</button> | |
<div id="output" style="margin-top:50px;"></div> | |
</div> | |
<div class="col-4"></div> | |
</div> | |
<script> | |
$('#load').click(function(){ | |
$.ajax({url: "ajax", success: function(result){ | |
var text=""; | |
//顯示幾筆新聞 | |
for (i = 0; i < $('input').val(); i++) { | |
text += "<p>" + (i+1) +". " + result['title'][i] + "</p>"; | |
} | |
$("#output").html("<div class='alert alert-secondary'>"+text+"</div>"); | |
}}); | |
}) | |
</script> | |
</body> | |
</html> |
from django.conf.urls import url | |
from . import views | |
urlpatterns = [ | |
url(r'^$', views.index, name='index'), | |
url(r'^ajax$', views.ajax, name='ajax') | |
] |
from django.shortcuts import render | |
from django.http import JsonResponse | |
from bs4 import BeautifulSoup | |
import requests | |
def index(request): | |
return render(request, 'news/index.html', {}) | |
def ajax(request): | |
""" | |
get data from google news sports today | |
return 'ajax form' | |
""" | |
html = requests.get( | |
'https://news.google.com/news/rss/headlines/section/topic/SPORTS.zh-TW_tw/%E9%AB%94%E8%82%B2?ned=tw&hl=zh-tw&gl=TW') | |
h = BeautifulSoup(html.text, 'html.parser') | |
items = h.find_all('item') | |
data = { | |
'title': [], | |
} | |
# append each news | |
for idx, item in enumerate(items): | |
data['title'].append(item.title.text) | |
return JsonResponse(data) |