詳解用python實現爬取CSDN熱門評論URL並存入redis
一、配置webdriver
下載谷歌瀏覽器驅動,並配置好
import time import random from PIL import Image from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC if __name__ == '__main__': options = webdriver.ChromeOptions() options.binary_location = r'C:\Users\hhh\AppData\Local\Google\Chrome\Application\谷歌瀏覽器.exe' # driver=webdriver.Chrome(executable_path=r'D:\360Chrome\chromedriver\chromedriver.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 BeautifulSoup from 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_herf title = html.xpath('//*[@id="feedlist_id"]/li/div/div/h2/a/@href')
可以看到,一下爬取瞭很多,速度非常快
三、寫入Redis
導入redis包後,配置redis端口和redis數據庫,用rpush函數寫入
打開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)
大功告成!
在Redis Desktop Manager中可以看到,爬取和寫入都是非常的快。
要使用隻需用rpop出棧就OK
one_url = r_link.rpop("csdn_url)") while one_url: print("{}被彈出!".format(one_url))
到此這篇關於詳解用python實現爬取CSDN熱門評論URL並存入redis的文章就介紹到這瞭,更多相關python爬取URL內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- None Found