欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python爬取盤搜的有效鏈接實(shí)現(xiàn)代碼

 更新時(shí)間:2019年07月20日 09:58:42   作者:小小滬  
這篇文章主要介紹了python爬取盤搜的有效鏈接,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下

因?yàn)楸P搜搜索出來(lái)的鏈接有很多已經(jīng)失效了,影響找數(shù)據(jù)的效率,因此想到了用爬蟲來(lái)過(guò)濾出有效的鏈接,順便練練手~

這是本次爬取的目標(biāo)網(wǎng)址http://www.pansou.com,首先先搜索個(gè)python,之后打開開發(fā)者工具,

可以發(fā)現(xiàn)這個(gè)鏈接下的json數(shù)據(jù)就是我們要爬取的數(shù)據(jù)了,把多余的參數(shù)去掉,

剩下的鏈接格式為http://106.15.195.249:8011/search_new?q=python&p=1,q為搜索內(nèi)容,p為頁(yè)碼

以下是代碼實(shí)現(xiàn):

import requests
import json
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import Queue
import sys
headers = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
}
q1 = Queue()
q2 = Queue()
urls = [] # 存取url列表
# 讀取url
def get_urls(query):
  # 遍歷50頁(yè)
  for i in range(1,51):
    # 要爬取的url列表,返回值是json數(shù)據(jù),q參數(shù)是搜索內(nèi)容,p參數(shù)是頁(yè)碼
    url = "http://106.15.195.249:8011/search_new?&q=%s&p=%d" % (query,i)
    urls.append(url)
# 獲取數(shù)據(jù)
def get_data(url):
  print("開始加載,請(qǐng)等待...")
  # 獲取json數(shù)據(jù)并把json數(shù)據(jù)轉(zhuǎn)換為字典
  resp = requests.get(url, headers=headers).content.decode("utf-8")
  resp = json.loads(resp)
  # 如果搜素?cái)?shù)據(jù)為空就拋出異常停止程序
  if resp['list']['data'] == []:
    raise Exception
  # 遍歷每一頁(yè)數(shù)據(jù)的長(zhǎng)度
  for num in range(len(resp['list']['data'])):
    # 獲取百度云鏈接
    link = resp['list']['data'][num]['link']
    # 獲取標(biāo)題
    title = resp['list']['data'][num]['title']
    # 訪問(wèn)百度云鏈接,判斷如果頁(yè)面源代碼中有“失效時(shí)間:”這段話的話就表明鏈接有效,鏈接無(wú)效的頁(yè)面是沒有這段話的
    link_content = requests.get(link, headers=headers).content.decode("utf-8")
    if "失效時(shí)間:" in link_content:
      # 把標(biāo)題放進(jìn)隊(duì)列1
      q1.put(title)
      # 把鏈接放進(jìn)隊(duì)列2
      q2.put(link)
      # 寫入csv文件
      with open("wangpanziyuan.csv", "a+", encoding="utf-8") as file:
        file.write(q1.get()+","+q2.get() + "\n")
  print("ok")
if __name__ == '__main__':
  # 括號(hào)內(nèi)填寫搜索內(nèi)容
  get_urls("python")
  # 創(chuàng)建線程池
  pool = ThreadPool(3)
  try:
    results = pool.map(get_data, urls)
  except Exception as e:
    print(e)
  pool.close()
  pool.join()
  print("退出")

總結(jié)

以上所述是小編給大家介紹的python爬取盤搜的有效鏈接實(shí)現(xiàn)代碼希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

最新評(píng)論