国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python爬蟲_微信公眾號推送信息爬取的實例

2020-02-16 10:27:02
字體:
供稿:網(wǎng)友

問題描述

利用搜狗的微信搜索抓取指定公眾號的最新一條推送,并保存相應(yīng)的網(wǎng)頁至本地。

注意點

搜狗微信獲取的地址為臨時鏈接,具有時效性。

公眾號為動態(tài)網(wǎng)頁(JavaScript渲染),使用requests.get()獲取的內(nèi)容是不含推送消息的,這里使用selenium+PhantomJS處理

代碼

#! /usr/bin/env python3from selenium import webdriverfrom datetime import datetimeimport bs4, requestsimport os, time, sys# 獲取公眾號鏈接def getAccountURL(searchURL): res = requests.get(searchURL) res.raise_for_status() soup = bs4.BeautifulSoup(res.text, "lxml") # 選擇第一個鏈接 account = soup.select('a[uigs="account_name_0"]') return account[0]['href']# 獲取首篇文章的鏈接,如果有驗證碼返回Nonedef getArticleURL(accountURL): browser = webdriver.PhantomJS("/Users/chasechoi/Downloads/phantomjs-2.1.1-macosx/bin/phantomjs") # 進(jìn)入公眾號 browser.get(accountURL) # 獲取網(wǎng)頁信息 html = browser.page_source accountSoup = bs4.BeautifulSoup(html, "lxml") time.sleep(1) contents = accountSoup.find_all(hrefs=True) try:  partitialLink = contents[0]['hrefs']  firstLink = base + partitialLink except IndexError:  firstLink = None   print('CAPTCHA!') return firstLink# 創(chuàng)建文件夾存儲html網(wǎng)頁,以時間命名def folderCreation(): path = os.path.join(os.getcwd(), datetime.now().strftime('%Y-%m-%d_%H-%M-%S')) try:  os.makedirs(path) except OSError as e:  if e.errno != errno.EEXIST:   raise  print("folder not exist!") return path# 將html頁面寫入本地def writeToFile(path, account, title): myfile = open("{}/{}_{}.html".format(path, account, title), 'wb') myfile.write(res.content) myfile.close()base ='https://mp.weixin.qq.com'accountList = ['央視新聞', '新浪新聞','鳳凰新聞','羊城晚報']query = 'http://weixin.sogou.com/weixin?type=1&s_from=input&query='path = folderCreation()for index, account in enumerate(accountList): searchURL = query + account accountURL = getAccountURL(searchURL) time.sleep(10) articleURL = getArticleURL(accountURL) if articleURL != None:  print("#{}({}/{}): {}".format(account, index+1, len(accountList), accountURL))  # 讀取第一篇文章內(nèi)容  res = requests.get(articleURL)  res.raise_for_status()  detailPage = bs4.BeautifulSoup(res.text, "lxml")  title = detailPage.title.text  print("標(biāo)題: {}/n鏈接: {}/n".format(title, articleURL))  writeToFile(path, account, title) else:  print('{} files successfully written to {}'.format(index, path))  sys.exit()print('{} files successfully written to {}'.format(len(accountList), path))

參考輸出

Terminal輸出

Finder

分析

鏈接獲取

首先進(jìn)入搜狗的微信搜索頁面,在地址欄中提取需要的部分鏈接,字符串連接公眾號名稱,即可生成請求鏈接

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 衡水市| 新乡市| 墨竹工卡县| 汝州市| 龙川县| 长阳| 蓝山县| 五寨县| 邯郸市| 陈巴尔虎旗| 和平县| 元氏县| 清原| 邛崃市| 淮阳县| 灵璧县| 赤城县| 通城县| 河曲县| 长岭县| 海南省| 台北县| 嘉善县| 湘潭市| 颍上县| 浙江省| 乌拉特中旗| 东阿县| 铁岭县| 宝山区| 宁化县| 勃利县| 凌海市| 北安市| 犍为县| 平塘县| 高台县| 台东市| 收藏| 集贤县| 苏尼特右旗|