首頁  >  文章  >  資料庫  >  如何用python實現爬取CSDN熱門評論URL並存入redis

如何用python實現爬取CSDN熱門評論URL並存入redis

WBOY
WBOY轉載
2023-05-28 15:17:23829瀏覽

一、設定webdriver

下載Google瀏覽器驅動程式,並設定好

import timeimport randomfrom PIL import Imagefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECif __name__ == '__main__':options = webdriver.ChromeOptions()options.binary_location = r'C:UsershhhAppDataLocalGoogleChromeApplication谷歌浏览器.exe'# driver=webdriver.Chrome(executable_path=r'D:360Chromechromedriverchromedriver.exe')driver = webdriver.Chrome(options=options)#以java模块为例driver.get('https://www.csdn.net/nav/java')for i in range(1,20):driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")time.sleep(2)

二、取得URL

from bs4 import BeautifulSoupfrom lxml import etree 
html = etree.HTML(driver.page_source)# soup = BeautifulSoup(html, 'lxml')# soup_herf=soup.find_all("#feedlist_id > li:nth-child(1) > div > div > h2 > a")# soup_herftitle = html.xpath('//*[@id="feedlist_id"]/li/div/div/h2/a/@href')

可以看到,一下爬取了很多,速度非常快
如何用python實現爬取CSDN熱門評論URL並存入redis

三、寫入Redis

導入redis包後,配置redis端口和redis數據庫& #xff0c;用rpush函數寫入
開啟redis如何用python實現爬取CSDN熱門評論URL並存入redis

import redis
r_link = redis.Redis(port='6379', host='localhost', decode_responses=True, db=1)for u in title:print("准备写入{}".format(u))r_link.rpush("csdn_url", u)print("{}写入成功!".format(u))print('=' * 30, 'n', "共计写入url:{}个".format(len(title)), 'n', '=' * 30)

如何用python實現爬取CSDN熱門評論URL並存入redis

大功告成!

在Redis Desktop Manager中可以看到,爬取和寫入都是非常的快。
如何用python實現爬取CSDN熱門評論URL並存入redis
要使用只要用rpop出棧就OK

one_url = r_link.rpop("csdn_url)")while one_url:print("{}被弹出!".format(one_url))

以上是如何用python實現爬取CSDN熱門評論URL並存入redis的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除