們?cè)诰W(wǎng)上瀏覽某些網(wǎng)站的文章時(shí),在文章的結(jié)尾處,都會(huì)有一個(gè)點(diǎn)贊的按鈕,如果覺(jué)得文章內(nèi)容非常不錯(cuò),就可以點(diǎn)擊這個(gè)“點(diǎn)贊”按鈕,給這篇文章進(jìn)行點(diǎn)贊一下。在wordpress網(wǎng)站的模板主題開(kāi)發(fā)中,我們可不可以也為我們wordpress網(wǎng)站的文章添加上這個(gè)“點(diǎn)贊”功能呢?答案是肯定的。那么,怎樣給wordpress網(wǎng)站的文章添加“點(diǎn)贊”功能呢?看我是怎樣實(shí)現(xiàn)的吧。
為了在點(diǎn)擊“點(diǎn)贊”按鈕時(shí),能夠向后臺(tái)傳遞數(shù)據(jù),我們這里要用到j(luò)query的AJAX處理函數(shù),所以,我們要先在wordpress模板的頭部文件中引入這個(gè)jquery文件,我這里是jquery1.7.2版本,其它版本也可以。代碼如下:
<script src="<?php bloginfo("template_url"); ?>/js/jquery-1.7.2.min.js"></script>
<div class="item single_praise">點(diǎn)贊:<span class="dashicons-before dashicons-heart"></span><span class="praise_num"><?php$praise_num = get_post_meta($post->ID,'post_praise')[0]; //獲取點(diǎn)贊數(shù)echo $praise_num ? $praise_num : 0;?></span></div>
我們要給這個(gè)“點(diǎn)贊”按鈕添加一個(gè)事件,只要一點(diǎn)擊這個(gè)“點(diǎn)贊”按鈕,就彈出相應(yīng)的事件處理,把當(dāng)前文章的ID號(hào)通過(guò)AJAX傳遞到single_praise.php文件中。代碼如下:
<script type="text/javascript">$(function(){var pid = <?php echo $post->ID; ?>; //文章IDvar user = '<?php echo wp_get_current_user()->user_login; ?>'; //當(dāng)前登錄的用戶名
$(".single_praise").click(function(){
$.ajax({type:'post',url:'<?php bloginfo("template_url"); ?>/include/single_praise.php',data:{ pid:pid,user:user },success:function(e){ console.log(e)var num = e ? e : 0;$(".praise_num").html(num); //把點(diǎn)贊重新寫(xiě)入
}})})})</script>
在wordpress模板目錄下的include目錄的下面,創(chuàng)建一個(gè)single_praise.php文件,用來(lái)接收AJAX傳遞過(guò)來(lái)的數(shù)據(jù),然后,向wordpress數(shù)據(jù)庫(kù)里添加或修改數(shù)據(jù)(文章的點(diǎn)贊數(shù)據(jù))。代碼如下:
<?phpdefine('BASE_PATH',str_replace( '\' , '/' , realpath(dirname(__FILE__).'/../../../../')));//獲取根目錄require(BASE_PATH.'/wp-load.php' );$postid = esc_sql($_POST['pid']);$user = esc_sql($_POST['user']);$u_ip = $_SERVER["REMOTE_ADDR"];if($postid==0 ){ //如果文章ID=0exit("非法操作");}//向數(shù)據(jù)庫(kù)中添加點(diǎn)贊數(shù)據(jù)$praise_num = get_post_meta($postid,'post_praise')[0];$user_views = !empty($praise_num) ? $praise_num : 0;update_post_meta($postid,'post_praise',$user_views+1);print_r($praise_num); exit;
通過(guò)上面的五步,我們就給wordpress網(wǎng)站的文章添加了點(diǎn)贊功能,我們每點(diǎn)擊一次,就會(huì)給文章的點(diǎn)贊數(shù)據(jù)+1。這樣,我們就基本上完成了操作。但是,有一個(gè)美中不足的地方,同一個(gè)用戶,如果連續(xù)點(diǎn)擊這個(gè)“點(diǎn)贊”按鈕,就會(huì)不停地增加點(diǎn)贊數(shù),這樣不太友好。
avascript實(shí)現(xiàn)直播網(wǎng)頁(yè)中常用到的點(diǎn)贊效果,如下圖:
代碼
js:
私信小編01即可獲取大量Python學(xué)習(xí)資料
因?yàn)槲抑車(chē)男』锇閭兲焯旄艺f(shuō)的最多的一句話就是:空間第一條點(diǎn)贊。
所以說(shuō)我還不如直接做一個(gè)自動(dòng)點(diǎn)贊的代碼呢,免得天天催我點(diǎn)贊。
首先既然是對(duì) QQ空間的一系列操作,自然是先解決登陸方面,在這篇文章里面我就不過(guò)多介紹了,因?yàn)槲疑蠋灼谥皩?duì)QQ空間已經(jīng)做了一定的介紹了。直接放出鏈接就好。歡迎看博主以前的文章
def search_cookie():
qq_number = input('請(qǐng)輸入qq號(hào):')
if not __import__('os').path.exists('cookie_dict.txt'):
get_cookie_json(qq_number)
with open('cookie_dict.txt', 'r') as f:
cookie=json.load(f)
return True
def get_cookie_json(qq_number):
password = __import__('getpass').getpass('請(qǐng)輸入密碼:')
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
login_url = 'https://i.qq.com/'
chrome_options =Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(options=chrome_options)
driver.get(login_url)
driver.switch_to_frame('login_frame')
driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()
time.sleep(1)
driver.find_element_by_xpath('//*[@id="u"]').send_keys(qq_number)
driver.find_element_by_xpath('//*[@id="p"]').send_keys(password)
time.sleep(1)
driver.find_element_by_xpath('//*[@id="login_button"]').click()
time.sleep(1)
cookie_list = driver.get_cookies()
cookie_dict = {}
for cookie in cookie_list:
if 'name' in cookie and 'value' in cookie:
cookie_dict[cookie['name']] = cookie['value']
with open('cookie_dict.txt', 'w') as f:
json.dump(cookie_dict, f)
return True
def get_g_tk():
p_skey = self.cookie['p_skey']
h = 5381
for i in p_skey:
h += (h << 5) + ord(i)
g_tk = h & 2147483647
當(dāng)我們拿到cookie信息和g_tk這個(gè)參數(shù)之后,繼續(xù)去尋找空間好友動(dòng)態(tài)的XML在何處。
首先點(diǎn)到XML位置一個(gè)個(gè)查找,發(fā)現(xiàn)有一個(gè)feeds3_html_more很像,點(diǎn)進(jìn)去發(fā)現(xiàn)的確是我們要找的url鏈接。
這個(gè)鏈接所需要的參數(shù)有很多,在這里列舉出來(lái)
這些參數(shù)中類似于可變參數(shù)的一共有五個(gè)。
def get_space():
your_url = 'https://user.qzone.qq.com/' + str(qq_number)
html = requests.get(your_url,headers=headers,cookies=cookie)
if html.status_code == 200:
qzonetoken = re.findall('window.g_qzonetoken =(.*?);',html.text,re.S)[1].split('"')[1]
return True
'rd': '0.9311604844249088',
'windowId': '0.51158950324406',
'usertime': str(round(time.time() * 1000)),
def get_g_tk():
p_skey = self.cookie['p_skey']
h = 5381
for i in p_skey:
h += (h << 5) + ord(i)
g_tk = h & 2147483647
我們拿到XML以及各個(gè)參數(shù)后,即可訪問(wèn)該網(wǎng)頁(yè)獲取其返回值了。
但是這個(gè)返回與其他的有一些不同的是,它不僅僅是個(gè)json文件,我們無(wú)法獲取后直接轉(zhuǎn)換成字典格式去給我們使用,這就很麻煩。
我們獲取字符串后,首先先將前后不一致的都切片扔掉,之后經(jīng)過(guò)一系列處理后發(fā)現(xiàn),我們很難將這個(gè)看似像json格式的字符串轉(zhuǎn)換成字典。
在這里我繼續(xù)介紹一個(gè)第三方庫(kù)demjson。
demjson 可以解決不正常的json格式數(shù)據(jù)
demjson的使用方法很簡(jiǎn)單。
encode將 Python 對(duì)象編碼成 JSON 字符串decode將已編碼的 JSON 字符串解碼為 Python 對(duì)象
# 例子
# -*- coding: utf-8 -*-
import demjson
js_json = "{x:1, y:2, z:3}"
py_json1 = "{'x':1, 'y':2, 'z':3}"
py_json2 = '{"x":1, "y":2, "z":3}'
data = demjson.decode(js_json)
print(data)
# {'y': 2, 'x': 1, 'z': 3}
data = demjson.decode(py_json1)
print(data)
# {'y': 2, 'x': 1, 'z': 3}
data = demjson.decode(py_json2)
print(data)
# {'y': 2, 'x': 1, 'z': 3}
我們使用demjson直接將該字符串轉(zhuǎn)換為耳熟能詳?shù)淖值涓袷剑崛∑渲械膁ata的data,即為前八條動(dòng)態(tài)的每個(gè)參數(shù),但我們這里只要第一個(gè)說(shuō)說(shuō)的動(dòng)態(tài)信息。
text = html.text[10:-2].replace(" ", "").replace('\n','')
json_list = demjson.decode(text)['data']['data']
qq_spaces = json_list[0]
我們拿到其信息后,先提取一些我們比較想知道的東西,比如名字、QQ號(hào)、發(fā)布時(shí)間、所獲贊數(shù)、說(shuō)說(shuō)內(nèi)容、說(shuō)說(shuō)地址等等結(jié)果。
在 qq_spaces 參數(shù)中我們發(fā)現(xiàn)里面有一個(gè)很長(zhǎng)也很特殊的一個(gè)結(jié)果是 html 結(jié)果,這個(gè)結(jié)果里面很長(zhǎng),簡(jiǎn)單來(lái)看是個(gè)網(wǎng)頁(yè)常規(guī)代碼,應(yīng)該是被JavaScript寫(xiě)入到網(wǎng)頁(yè)中了,既然不是全部代碼,那么只能用正則提取一下里面的具體我們需要的東西了。
content = str(qq_spaces['html'])
try:zanshu = re.findall('<spanclass="f-like-cnt">(.*?)</span>人覺(jué)得很贊</div>',content,re.S)[0]
except:return None
time_out = str(qq_spaces['feedstime'])
print("名字:"+str(qq_spaces['nickname']))
print("QQ號(hào):"+str(qq_spaces['opuin']))
print("時(shí)間:"+time_out)
print('贊數(shù):'+zanshu)
times = qq_spaces['abstime']
his_url = re.findall('data-curkey="(.*?)"',content,re.S)[0]
在QQ空間隨便找個(gè)好友點(diǎn)個(gè)贊吧,這樣我們才能接收到請(qǐng)求。
我們首先清空原來(lái)動(dòng)態(tài)產(chǎn)生的抓包,直接點(diǎn)個(gè)贊發(fā)現(xiàn)關(guān)于dolike的url只有三個(gè),第一個(gè)是個(gè)POST請(qǐng)求,應(yīng)該是我們所需要的點(diǎn)贊網(wǎng)址。
我們獲取到URL后,找到里面所需要的參數(shù)。發(fā)現(xiàn)一共有十一個(gè)參數(shù),在這里猜測(cè)應(yīng)該不存在加密參數(shù)。
既然參數(shù)沒(méi)什么問(wèn)題那就直接寫(xiě)代碼吧。
def get_zan(times,his_url):
data = {'g_tk': g_tk,'qzonetoken': qzonetoken}
post_data = {
'qzreferrer': 'https://user.qzone.qq.com/'+str(qq_number),
'opuin': str(qq_number),
'unikey': str(his_url),
'curkey': str(his_url),
'from': '1',
'appid': '311',
'typeid': '0',
'abstime': str(times),
'fid': str(his_url).split('/')[-1],
'active': '0',
'fupdate': '1'
}
url = 'https://user.qzone.qq.com/proxy/domain/w.qzone.qq.com/cgi-bin/likes/internal_dolike_app?'
url = url + urllib.parse.urlencode(data)
html = requests.post(url,headers=headers,cookies=cookie,data=post_data)
if html.status_code == 200:print("點(diǎn)贊成功" if len(html.text) == 469 else "點(diǎn)贊失敗")
因?yàn)闃?shù)莓派并不是很不錯(cuò)的問(wèn)題,這個(gè)代碼做不到絕對(duì)的秒贊。
def run_tolike():
if os.path.exists('time_out.txt'):
with open('time_out.txt','r') as f:
time_out = f.read()
else:time_out = None
while True:
get_friends_list()
time.sleep(__import__('random').randint(0,5)) # 秒贊?
if not time_out or time_out != time_out:
time_out = time_out
get_zan(times,his_url)
return True
else:log('說(shuō)說(shuō)無(wú)更新,等待中...')
with open('time_out.txt','w') as f:
f.write(str(times))
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。