您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:详解用python实现爬取CSDN热门评论URL并存入redis

51自学网 2021-10-30 22:46:38
  python
这篇教程详解用python实现爬取CSDN热门评论URL并存入redis写得很实用,希望能帮到您。

一、配置webdriver

下载谷歌浏览器驱动,并配置好

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:/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 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')

可以看到,一下爬取了很多,速度非常快

在这里插入图片描述

三、写入Redis

导入redis包后,配置redis端口和redis数据库,用rpush函数写入
打开redis

在这里插入图片描述

import redisr_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内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


python之Django自动化资产扫描的实现
Python合并Excel表(多sheet)的实现
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。