1. 程式人生 > >檢測百度精選(專業)問答是否生效

檢測百度精選(專業)問答是否生效

 百度最近推出了精選問答功能,即更新文章,稽核通過即可展現在移動端第一位。如果多人做同一個詞,那麼進行輪流展現。

接著進入正題,因為百度精選問答存在著不生效或者未稽核通過的問題,因此也就誕生了檢測精選問答是否生效的需求,因此再進行改進,但是如果手工一個一個查詢,要是查詢數量又很多,那麼就要命了。故而這段程式碼就誕生了,這裡謝謝陳東堯,因為這的程式碼在他的基礎上改進的。

實現原理:查詢關鍵詞排名是否在第一位判斷精選問答是否生效,非常簡單。

PS:因為百度精選問答實現輪展機制,故而並不能達到百分之百正確。

程式碼奉上,也歡迎提出建議!

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib
from urllib import request,error,parse
import requests # 需要用pip命令安裝requests模組
import time
import re
import random

uaList = ['Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36']
ua = random.choice(uaList)
key_url=[]
key_word=[]

def download(url,timeout=10,user_agent='dyspider',proxy=None,num_retries=5):
    """
    通用網頁原始碼下載函式
    :param url: 要下載的url
    :param timeout: 請求超時時間,單位/秒。可能某些網站的反應速度很慢,所以需要一個連線超時變數來處理。
    :param user_agent: 使用者代理資訊,可以自定義是爬蟲還是模擬使用者
    :param proxy: ip代理(http代理),訪問某些國外網站的時候需要用到。必須是雙元素元組或列表(‘ip:埠’,‘http/https’)
    :param num_retries: 失敗重試次數
    :return: HTML網頁原始碼
    """
    headers = {'User-Agent':user_agent}
    request = urllib.request.Request(url,headers=headers)
    if proxy: # 如果有代理值,可以通過set_proxy方法新增上
        proxy_host,proxy_type = proxy # 對proxy值進行解包
        request.set_proxy(proxy_host,proxy_type)
    print('Downloading:',url)
    try:
        # 開啟網頁並讀取內容存入html變數中
        html = urllib.request.urlopen(request,timeout=timeout).read().decode('utf-8')
    except urllib.error.URLError as err:
        print('Download error:',err.reason)
        html = None # 如果有異常,那麼html肯定是沒獲取到的,所以賦值None
        if num_retries > 0:
            if hasattr(err,'code') and 500 <= err.code <= 600:
                return download(url,timeout,user_agent,proxy,num_retries-1)
    return html

def createKey():   #create baidu URL with search words
    with open('關鍵詞.txt') as f:
        for key in f:
            key_word.append(key)

if __name__ == '__main__':
    createKey()
    with open('WAP-排名結果.txt', 'a', encoding='utf-8') as f:
        f.write('***********'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'***********'+'\n')
    for k in key_word:
        t = 0
        key_url = parse.quote(k.strip())
        for p in range(0,11,10): # 第二個引數設定頁數(前二頁11,前三頁21,前四頁31,以此類推。)
            url = 'https://m.baidu.com/s?wd=%s&pn=%d&rn=10' % (key_url,p)
            html = download(url, user_agent=ua)
            a = re.findall(r"'order':'(\d+)','waplogo':1,'mu':'(.*?)'", html, re.S | re.I)
            for i in a:
                if 'm.gaodun.com/zhongji' in i[1]:  # 這裡指定需要檢測的網址
                    with open('WAP-排名結果.txt', 'a', encoding='utf-8') as f:

                        line = k.strip() + '\t' + '第%s名:' % i[0] + i[1] + '\n'
                        f.write(line)
                        f.flush()
                        t = 1
                        break
                else:
                    continue
            if t == 1:
                break
            else:
                continue
        if t==0:
            with open('WAP-排名結果.txt', 'a', encoding='utf-8') as f:
                line = k.strip() + '\t' + '排名>10'+ '\n'
                f.write(line)
                f.flush()
    print('完成!')