作者:
楊平、舒婷
資料來源: Citytalk城市通
輸入: 最新展覽
回復: 以輪播的方式顯示最新展覽的結果
1. 展覽資料為AJAX Request,頁面載入後才載入展覽資料
2. 需用POST送出Request,直接GET會拿不到東西
3. 此網站有做CSRF防護: 每個Session對應到一組CSRF Token,需在header中提供Session ID,以及CSRF Token,讓伺服器驗證
使用requests送出POST Request
1. 先取得Session ID,以及CSRF Token
2. 然後再用這組資料取得展覽資訊
import requests
from bs4 import BeautifulSoup
def get_datas():
client = requests.session()
r = client.get("https://www.citytalk.tw/cata")
phpsessid = client.cookies['PHPSESSID']
soup = BeautifulSoup(r.text, 'lxml')
csrf_token = soup.find('meta', attrs={'name':'csrf-token'})['content']
header = {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": "PHPSESSID=" + phpsessid,
"Host": "www.citytalk.tw",
"Origin": "https://www.citytalk.tw",
"Referer": "https://www.citytalk.tw/cata/",
"X-CSRF-Token": csrf_token
}
data = {
// data們
}
ex_data = requests.post("http://www.citytalk.tw/post/v3/cata/index", headers=header, data=data)
datas = ex_data.json()['data']
content = []
for i, data in enumerate(datas):
id = data['e_id']
title = data['title']
img = data['img']
text = '日期:' + data['e_start'] + '-' + data['e_end']
content.append({'title':title,
'url': 'https://www.citytalk.tw/event/' + id + '-'+ title.replace(' ', ''),
'img':'https://www.citytalk.tw' + img,
'text': text
})
return content
requests.session()
開啟一個session,讓session id可被保存下來
CSRF Token: 在html的meta裡面
for i, d in enumerate(datas):
column = CarouselColumn( # column裡面的內容
thumbnail_image_url = d['img'],
title = d['title'],
text = d['text'],
actions = [
URITemplateAction( #鏈接
label = '展覽介紹連結',
uri = d['url']
)
]
)
columns.append(column)
carousel_template_message = TemplateSendMessage(
alt_text = "展覽輪播",
template = CarouselTemplate(
columns = columns
)
)