selenium获取文章所有评论

mac2026-10-02  1

《网络爬虫:从入门到精通》第4.3.3节 selenium获取文章的所有评论 geckodriver.exe版本是geckodriver-v0.23.0-win64。 代码在 FireFox Developer Edition 71.0b5(64 位) 中测试通过,可以将1到16页所有评论提取出来,现在的代码是在作者给出的代码的基础上改动过来的,在此向他们致敬!

原来的代码中‘button.more-btn’已经失效,评论页的结构也已经变化,代码更新于2019年11月2日,用了2天时间终于搞出来了。

以下代码还利用了selenium的高级操作,限制了程序对css、图片及js脚本的限制,使爬取更快速。

from selenium import webdriver # Keys是keys包中命名的按键包的名字,区分大小写,而路径里面的keys包则需要根据安装路径中的keys包的名字来引入,否则将无法识别。 from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time geck_path = r'C:\Users\MasterWell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts\geckodriver.exe' fp = webdriver.FirefoxProfile() # 禁止css加载 fp.set_preference("permissions.default.stylesheet",2) # 限制图片加载 fp.set_preference("permissions.default.image",2) # 限制js脚本加载 #fp.set_preference("javascript.enabled", False) driver = webdriver.Firefox(firefox_profile=fp,executable_path = geck_path) driver.implicitly_wait(5) # 隐性等待 driver.get("http://www.santostang.com/2018/07/04/hello-world/") time.sleep(4) for i in range(1,17): # 下滑到页面底部 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 转换iframe driver.switch_to.frame(driver.find_element_by_xpath('.//div[@id="lv-container"]/iframe[2]')) if i > 11: x_path = './/div[@class="more-wrapper"]/button[' + str(i-9) + ']' else: x_path = './/div[@class="more-wrapper"]/button[' + str(i) + ']' click_btn = driver.find_element_by_xpath(x_path) # 点击前先按下tab键(其他按键也可以考虑),再进行单击可以解决因跳转点击时出现失去焦点而导致的click单击无效的情况 click_btn.send_keys(Keys.TAB) click_btn.click() # 切回主文档 driver.switch_to.default_content() time.sleep(3) # 转换iframe driver.switch_to.frame(driver.find_element_by_xpath('.//div[@id="lv-container"]/iframe[2]')) comments = driver.find_elements_by_css_selector('div.reply-content') print ("第" + str(i) + "页的评论内容是:") for eachcomment in comments: content = eachcomment.find_element_by_tag_name('p') print (content.text) # 切回主文档 driver.switch_to.default_content() time.sleep(4)

 

最新回复(0)