>  기사  >  데이터 베이스  >  Python을 사용하여 CSDN 인기 댓글 URL을 크롤링하고 이를 Redis에 저장하는 방법

Python을 사용하여 CSDN 인기 댓글 URL을 크롤링하고 이를 Redis에 저장하는 방법

WBOY
WBOY앞으로
2023-05-28 15:17:23825검색

1. 웹드라이버를 구성하세요

구글 크롬 드라이버를 다운로드해서 구성하세요

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)

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에 저장하는 방법

3. Redis에 쓰기

redis 패키지를 가져온 후 ,redis 포트 및 redis 데이터베이스 구성,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으로 튀어나오시면 됩니다

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

위 내용은 Python을 사용하여 CSDN 인기 댓글 URL을 크롤링하고 이를 Redis에 저장하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제