Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
們在網上瀏覽某些網站的文章時,在文章的結尾處,都會有一個點贊的按鈕,如果覺得文章內容非常不錯,就可以點擊這個“點贊”按鈕,給這篇文章進行點贊一下。在wordpress網站的模板主題開發中,我們可不可以也為我們wordpress網站的文章添加上這個“點贊”功能呢?答案是肯定的。那么,怎樣給wordpress網站的文章添加“點贊”功能呢?看我是怎樣實現的吧。
為了在點擊“點贊”按鈕時,能夠向后臺傳遞數據,我們這里要用到jquery的AJAX處理函數,所以,我們要先在wordpress模板的頭部文件中引入這個jquery文件,我這里是jquery1.7.2版本,其它版本也可以。代碼如下:
<script src="<?php bloginfo("template_url"); ?>/js/jquery-1.7.2.min.js"></script>
<div class="item single_praise">點贊:<span class="dashicons-before dashicons-heart"></span><span class="praise_num"><?php$praise_num = get_post_meta($post->ID,'post_praise')[0]; //獲取點贊數echo $praise_num ? $praise_num : 0;?></span></div>
我們要給這個“點贊”按鈕添加一個事件,只要一點擊這個“點贊”按鈕,就彈出相應的事件處理,把當前文章的ID號通過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; ?>'; //當前登錄的用戶名
$(".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); //把點贊重新寫入
}})})})</script>
在wordpress模板目錄下的include目錄的下面,創建一個single_praise.php文件,用來接收AJAX傳遞過來的數據,然后,向wordpress數據庫里添加或修改數據(文章的點贊數據)。代碼如下:
<?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("非法操作");}//向數據庫中添加點贊數據$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;
通過上面的五步,我們就給wordpress網站的文章添加了點贊功能,我們每點擊一次,就會給文章的點贊數據+1。這樣,我們就基本上完成了操作。但是,有一個美中不足的地方,同一個用戶,如果連續點擊這個“點贊”按鈕,就會不停地增加點贊數,這樣不太友好。
avascript實現直播網頁中常用到的點贊效果,如下圖:
代碼
js:
私信小編01即可獲取大量Python學習資料
因為我周圍的小伙伴們天天跟我說的最多的一句話就是:空間第一條點贊。
所以說我還不如直接做一個自動點贊的代碼呢,免得天天催我點贊。
首先既然是對 QQ空間的一系列操作,自然是先解決登陸方面,在這篇文章里面我就不過多介紹了,因為我上幾期之前對QQ空間已經做了一定的介紹了。直接放出鏈接就好。歡迎看博主以前的文章
def search_cookie():
qq_number = input('請輸入qq號:')
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('請輸入密碼:')
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
當我們拿到cookie信息和g_tk這個參數之后,繼續去尋找空間好友動態的XML在何處。
首先點到XML位置一個個查找,發現有一個feeds3_html_more很像,點進去發現的確是我們要找的url鏈接。
這個鏈接所需要的參數有很多,在這里列舉出來
這些參數中類似于可變參數的一共有五個。
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以及各個參數后,即可訪問該網頁獲取其返回值了。
但是這個返回與其他的有一些不同的是,它不僅僅是個json文件,我們無法獲取后直接轉換成字典格式去給我們使用,這就很麻煩。
我們獲取字符串后,首先先將前后不一致的都切片扔掉,之后經過一系列處理后發現,我們很難將這個看似像json格式的字符串轉換成字典。
在這里我繼續介紹一個第三方庫demjson。
demjson 可以解決不正常的json格式數據
demjson的使用方法很簡單。
encode將 Python 對象編碼成 JSON 字符串decode將已編碼的 JSON 字符串解碼為 Python 對象
# 例子
# -*- 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直接將該字符串轉換為耳熟能詳的字典格式,提取其中的data的data,即為前八條動態的每個參數,但我們這里只要第一個說說的動態信息。
text = html.text[10:-2].replace(" ", "").replace('\n','')
json_list = demjson.decode(text)['data']['data']
qq_spaces = json_list[0]
我們拿到其信息后,先提取一些我們比較想知道的東西,比如名字、QQ號、發布時間、所獲贊數、說說內容、說說地址等等結果。
在 qq_spaces 參數中我們發現里面有一個很長也很特殊的一個結果是 html 結果,這個結果里面很長,簡單來看是個網頁常規代碼,應該是被JavaScript寫入到網頁中了,既然不是全部代碼,那么只能用正則提取一下里面的具體我們需要的東西了。
content = str(qq_spaces['html'])
try:zanshu = re.findall('<spanclass="f-like-cnt">(.*?)</span>人覺得很贊</div>',content,re.S)[0]
except:return None
time_out = str(qq_spaces['feedstime'])
print("名字:"+str(qq_spaces['nickname']))
print("QQ號:"+str(qq_spaces['opuin']))
print("時間:"+time_out)
print('贊數:'+zanshu)
times = qq_spaces['abstime']
his_url = re.findall('data-curkey="(.*?)"',content,re.S)[0]
在QQ空間隨便找個好友點個贊吧,這樣我們才能接收到請求。
我們首先清空原來動態產生的抓包,直接點個贊發現關于dolike的url只有三個,第一個是個POST請求,應該是我們所需要的點贊網址。
我們獲取到URL后,找到里面所需要的參數。發現一共有十一個參數,在這里猜測應該不存在加密參數。
既然參數沒什么問題那就直接寫代碼吧。
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("點贊成功" if len(html.text) == 469 else "點贊失敗")
因為樹莓派并不是很不錯的問題,這個代碼做不到絕對的秒贊。
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('說說無更新,等待中...')
with open('time_out.txt','w') as f:
f.write(str(times))
*請認真填寫需求信息,我們會在24小時內與您取得聯系。