Python实现的爬取百度文库功能示例

本文实例讲述了Python实现的爬取百度文库功能。分享给大家供大家参考,具体如下:

# -*- coding: utf-8 -*-
from selenium import webdriver
from bs4 import BeautifulSoup
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH# 用来居中显示标题
from time import sleep
from selenium.webdriver.common.keys import Keys
# 浏览器安装路径
#BROWSER_PATH=\'C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chromedriver.exe'
#目的URL
DEST_URL='https://wenku.baidu.com/view/aa31a84bcf84b9d528ea7a2c.html'
#用来保存文档
doc_title = ''
doc_content_list = []
def find_doc(driver, init=True):
  global doc_content_list
  global doc_title
  stop_condition = False
  html = driver.page_source
  soup1 = BeautifulSoup(html, 'lxml')
  if (init is True): # 得到标题
    title_result = soup1.find('div', attrs={'class': 'doc-title'})
    doc_title = title_result.get_text() # 得到文档标题
    # 拖动滚动条
    init_page = driver.find_element_by_xpath( "//div[@class='foldpagewg-text-con']")
    print(type(init_page), init_page)
    driver.execute_script('arguments[0].scrollIntoView();', init_page)
    init_page.click()
    init = False
  else:
    try:
      page = driver.find_element_by_xpath( "//div[@class='pagerwg-schedule']")
      #print(type(next_page), next_page)
      next_page = driver.find_element_by_class_name("pagerwg-button")
      station = driver.find_element_by_xpath( "//div[@class='bottombarwg-root border-none']")
      driver.execute_script('arguments[0].scrollIntoView(false);', station)
      #js.executeScript("arguments[0].click();",next_page);
      #sleep(5)
      '''js = "window.scrollTo(508,600)"
      driver.execute_script(js)'''
      next_page.click()
    except:
      #结束条件
      print("找不到元素")
      stop_condition = True
      #next_page.send_keys(Keys.ENTER)
      # 遍历所有的txt标签标定的文档,将其空格删除,然后进行保存
  content_result = soup1.find_all('p', attrs={'class': 'txt'})
  for each in content_result:
    each_text = each.get_text()
    if ' ' in each_text:
      text = each_text.replace(' ', '')
    else:
      text = each_text
    # print(each_text)
    doc_content_list.append(text)
          # 得到正文内容
  sleep(2) # 防止页面加载过慢
  if stop_condition is False:
    doc_title, doc_content_list = find_doc(driver, init)
  return doc_title, doc_content_list
def save(doc_title, doc_content_list):
  document = Document()
  heading = document.add_heading(doc_title, 0)
  heading.alignment = WD_ALIGN_PARAGRAPH.CENTER # 居中显示
  for each in doc_content_list:
    document.add_paragraph(each)
  # 处理字符编码问题
  t_title = doc_title.split()[0]
  #print(t_title)
  #document.save('2.docx')
  document.save('百度文库-%s.docx'% t_title)
  print("\n\nCompleted: %s.docx, to read." % t_title)
  driver.quit()
if __name__ == '__main__':
  options = webdriver.ChromeOptions()
  options.add_argument('user-agent="Mozilla/5.0 (Linux; Android 4.0.4; \ Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) \ Chrome/18.0.1025.133 Mobile Safari/535.19"')
  #driver = webdriver.Chrome(BROWSER_PATH, chrome_options=options)
  driver = webdriver.Chrome(chrome_options=options)
  driver.get(DEST_URL)
  #JavascriptExecutor js = (JavascriptExecutor) driver;
  print("**********START**********")
  title, content = find_doc(driver, True)
  save(title, content)
  driver.quit()

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

(0)

相关推荐

  • centos6.5安装python3.7.1之后无法使用pip的解决方案

    编译安装全是坑-- 第一遍装完无法使用pip,报错找不到ssl模块.各种报错: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. ... configure: error: Invalid --with-openssl value ... 结果各种捣鼓. 1.注意cetos6.5自带的openssl版本是1.0.1,需要升级到1.0.2

  • Python从文件中读取数据的方法讲解

    编写了一个名为learning_python.txt的文件,内容如下: [root@centos7 tmp]# cat learning_python.txt In Python you can code; In Python you can learn object; In Python you can learn class. 要求:编写一个程序,它读取这个文件并打印三次. 1.第一次打印时读取整个文件: 2.第二次打印时遍历文件对象: 3.第三次打印时将各行存储在一个列表中,再在with代

  • 使用Python自动化破解自定义字体混淆信息的方法实例

    注意:本示例仅供学习参考- 混淆原理 出于某种原因,明文信息通过自定义字体进行渲染,达到混淆目的. 举个例子: 网页源码 <p>123</p> 在正常字体的渲染下,浏览者看到的是 123 这 3 个数字. 如果创建一种自定义字体,把 1 渲染成 5,那么浏览者看到的便是 523 这 3 个数字. 这样便达到混淆信息的效果,常见于对付爬虫之类的自动化工具. 破解方法 下载自定义字体文件(通常在 css @font-face 中找到),保存成 a.ttf 文件. 安装以下依赖项目 te

  • Python标准库使用OrderedDict类的实例讲解

    目标:创建一个字典,记录几对python词语,使用OrderedDict类来写,并按顺序输出. 写完报错: [root@centos7 tmp]# python python_terms.py File "python_terms.py", line 9 from name,language in python_terms.items(): ^ SyntaxError: invalid syntax 代码如下: from collections import OrderedDict p

  • Python通过for循环理解迭代器和生成器实例详解

    本文实例讲述了Python通过for循环理解迭代器和生成器.分享给大家供大家参考,具体如下: 迭代器 可迭代对象 通过 for-in- 循环依次拿到数据进行使用的过程称为遍历,也叫迭代.我们把可以通过 for-in- 语句迭代读取数据的对象称之为可迭代对象. - 通过 isinstance()可以判断一个对象是否可以迭代 # 判断列表 print(isinstance([], Iterable) 打印结果为 True 即为可迭代对象. - 自定义一个能容纳数据的类,测试该类的可迭代性 impor

  • python获取交互式ssh shell的方法

    更新,最近在学unix环境编程,了解一下进程的创建过程,用最原始的方式实现了一个ssh命令的执行. #coding=utf8 ''' 用python实现了一个简单的shell,了解进程创建 类unix 环境下 fork和exec 两个系统调用完成进程的创建 ''' import sys, os def myspawn(cmdline): argv = cmdline.split() if len(argv) == 0: return program_file = argv[0] pid = os

  • Python实现的对本地host127.0.0.1主机进行扫描端口功能示例

    本文实例讲述了Python实现的对本地host127.0.0.1主机进行扫描端口功能.分享给大家供大家参考,具体如下: 前面一篇<Python IP端口扫描工具类>详细介绍了端口扫描功能,这里分析一下针对本地localhost端口扫描的方法. 具体代码如下: #!/usr/local/bin/python #-*- coding: UTF-8 -*- #端口扫描器 import socket import thread import time socket.setdefaulttimeout(

  • Python3使用requests模块实现显示下载进度的方法详解

    本文实例讲述了Python3使用requests模块实现显示下载进度的方法.分享给大家供大家参考,具体如下: 一.配置request 1. 相关资料 请求关键参数:stream=True.默认情况下,当你进行网络请求后,响应体会立即被下载.你可以通过 stream 参数覆盖这个行为,推迟下载响应体直到访问 Response.content 属性. tarball_url = 'https://github.com/kennethreitz/requests/tarball/master' r =

  • Python基础之文件读取的讲解

    with open(filename) as fp: dataMat = [] for line in fp.readlines(): # fp.readlines()返回一个list,list of strs # 也即line类型为`str` curLine = line.strip().split('\t') # 只有`str`类型才有strip()成员函数, # 在经过split()分割,得到list类型 # 也即curLine类型为list # curLine 仍然是由字符串构成的lis

  • Python中整数的缓存机制讲解

    在python中,如下代码结果一定不会让你吃惊: Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> a=345 >>> b=a >

随机推荐