1. # -*- coding:UTF-8 -*-
  2. from urllib import request
  3. from bs4 import BeautifulSoup
  4. import re
  5. import sys
  6.  
  7. if __name__ == "__main__":
  8. #创建txt文件
  9. file = open('一念永恒.txt', 'w', encoding='utf-8')
  10. #一念永恒小说目录地址
  11. target_url = 'http://www.biqukan.com/1_1094/'
  12. #User-Agent
  13. head = {}
  14. head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
  15. target_req = request.Request(url = target_url, headers = head)
  16. target_response = request.urlopen(target_req)
  17. target_html = target_response.read().decode('gbk','ignore')
  18. #创建BeautifulSoup对象
  19. listmain_soup = BeautifulSoup(target_html,'lxml')
  20.  
  21. #搜索文档树,找出div标签中class为listmain的所有子标签
  22. chapters = listmain_soup.find_all('div',class_ = 'listmain')
  23. #使用查询结果再创建一个BeautifulSoup对象,对其继续进行解析
  24. download_soup = BeautifulSoup(str(chapters), 'lxml')
  25. #计算章节个数
  26. numbers = (len(download_soup.dl.contents) - 1) / 2 - 8
  27. index = 1
  28. #开始记录内容标志位,只要正文卷下面的链接,最新章节列表链接剔除
  29. begin_flag = False
  30. #遍历dl标签下所有子节点
  31. for child in download_soup.dl.children:
  32. #滤除回车
  33. if child != '\n':
  34. #找到《一念永恒》正文卷,使能标志位
  35. if child.string == u"《一念永恒》正文卷":
  36. begin_flag = True
  37. #爬取链接并下载链接内容
  38. if begin_flag == True and child.a != None:
  39. download_url = "http://www.biqukan.com" + child.a.get('href')
  40. download_req = request.Request(url = download_url, headers = head)
  41. download_response = request.urlopen(download_req)
  42. download_html = download_response.read().decode('gbk','ignore')
  43. download_name = child.string
  44. soup_texts = BeautifulSoup(download_html, 'lxml')
  45. texts = soup_texts.find_all(id = 'content', class_ = 'showtxt')
  46. soup_text = BeautifulSoup(str(texts), 'lxml')
  47. write_flag = True
  48. file.write(download_name + '\n\n')
  49. #将爬取内容写入文件
  50. for each in soup_text.div.text.replace('\xa0',''):
  51. if each == 'h':
  52. write_flag = False
  53. if write_flag == True and each != ' ':
  54. file.write(each)
  55. if write_flag == True and each == '\r':
  56. file.write('\n')
  57. file.write('\n\n')
  58. #打印爬取进度
  59. sys.stdout.write("已下载:%.3f%%" % float(index/numbers) + '\r')
  60. sys.stdout.flush()
  61. index += 1
  62. file.close()

>>> for link in soup.find_all('a'):
... print(link.get('href'))
#用于爬取a标签的链接

  

Beautiful Soup 4.4.0 文档链接:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

已下文章来自博客园大佬:http://www.cnblogs.com/sakura3/p/8460224.html(为了复习方便,搬一下,谢谢)

爬小说:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import requests
  4. from bs4 import BeautifulSoup
  5. # get_url_list 获取所有章节的URL,在一个list里
  6. def get_url_list(url):
  7. content = requests.get(url).content #获取页面内容
  8. soup = BeautifulSoup(content,'lxml') #Beautifulsoup 实例化对象
  9. url_list = [] #空的url_list 数组
  10. # urls = soup.find('div',{'id':'list'}).find('dl').find_all('dd')
  11. urls = soup.select('#list > dl > dd > a') # 根据页面选择到URL ,还可以urls = soup.find('div',{'id':'list'}).find('dl').find_all('dd')
  12. for i in urls: #遍历里面的每一章的URL
  13. i = i.get('href') #获取URL
  14. # print(i)
  15. i = 'http://www.biquge.com.tw' + i #分析文章组成,形成最终的URL
  16. url_list.append(i) #添加到url_list 里面去
  17. # print (url_list)
  18. return url_list
  19. # 获取这一章的内容
  20. def get_data(url):
  21. content = requests.get(url).content
  22. soup = BeautifulSoup(content, 'lxml')
  23. f = open(r'C:\Users\HBX\Documents\staudy\HMXX.txt','a+',encoding='utf-8') #不加utf-8 会有编码报错
  24. text_name = soup.find('div',{'class':'bookname'}).find('h1').text #获得章节名字
  25. # text_content = soup.select('#content')
  26. text_content = soup.find('div',{'id':'content'}).get_text() #获得章节内容 ,还有一种select css 选择的获取章节内容的方式
  27. book =text_name+ '\r\n' + text_content #整体的一章
  28. # print(book)
  29. f.write((book)+'\r\n') #换行写入
  30. f.close() #关闭文件
  31. # for x in text_content:
  32. # a = x.text.replace('readx();', '')
  33. # print(a)
  34.  
  35. if __name__ =='__main__':
  36. url = 'http://www.biquge.com.tw/18_18049/' #笔趣阁的小说目录页面
  37. url_list = get_url_list(url) #获取了所有的url
  38. for i in url_list: # 循环一章url
  39. get_data(i) #获取文章内容

BeautifulSoup的基本用法的更多相关文章

  1. bs4.BeautifulSoup的基础用法

    导入模块 from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html.parser") 下面看下常见的用法 ...

  2. PYTHON 爬虫笔记五:BeautifulSoup库基础用法

    知识点一:BeautifulSoup库详解及其基本使用方法 什么是BeautifulSoup 灵活又方便的网页解析库,处理高效,支持多种解析器.利用它不用编写正则表达式即可方便实现网页信息的提取库. ...

  3. Beautifulsoup模块基础用法详解

    目录 Beautifulsoup模块 官方中文文档 介绍 基本使用 遍历文档树 搜索文档树 五种过滤器 **find_all( name , attrs , recursive , text , ** ...

  4. #爬虫必备,解析html文档----beautifulsoup的简单用法

    #出处:http://mp.weixin.qq.com/s?__biz=MjM5NzU0MzU0Nw==&mid=201820961&idx=2&sn=b729466f334d ...

  5. Python BeautifulSoup库的用法

    BeautifulSoup是一个可以从HTML或者XML文件中提取数据的Python库,它通过解析器把文档解析为利于人们理解的文档导航模式,有利于查找和修改文档. BeautifulSoup3目前已经 ...

  6. BeautifulSoup的简单用法

    官方文档加载比较慢(估计是我党的原因) https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-parents ...

  7. 孤荷凌寒自学python第七十天学习并实践beautifulsoup对象用法3

    孤荷凌寒自学python第七十天学习并实践beautifulsoup对象用法3 (完整学习过程屏幕记录视频地址在文末) 今天继续学习beautifulsoup对象的属性与方法等内容. 一.今天进一步了 ...

  8. 孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2

    孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2 (完整学习过程屏幕记录视频地址在文末) 今天继续学习beautifulsoup对象的属性与方法等内容. 一.今天进一步 ...

  9. 孤荷凌寒自学python第六十八天学习并实践beautifulsoup模块1

    孤荷凌寒自学python第六十八天学习并实践beautifulsoup模块1 (完整学习过程屏幕记录视频地址在文末) 感觉用requests获取到网页的html源代码后,更重要的工作其实是分析得到的内 ...

随机推荐

  1. vue-axios

    vue axios全攻略   不再继续维护vue-resource,并推荐大家使用 axios 开始,axios 被越来越多的人所了解.本来想在网上找找详细攻略,突然发现,axios 的官方文档本身就 ...

  2. Linux 01 计算机系统硬件组成简介

    PC服务器 1U = 4.445cm 企业1-2U比较多 互联网公司,品牌 DELL,HP, IBM. Dell品牌 2010年之前:1850,1950(1u),2850,2950(2u) 2010年 ...

  3. 使用AOP AspectJ 定义@Before,@After ,@Aroud后 执行两次

    背景 转眼之间,发现博客已经将近半年没更新了,甚是惭愧.话不多说,正如标题所言,最近在使用AspectJ的时候,发现拦截器(AOP切面)执行了两次了.我们知道,AspectJ是AOP的一种解决方案,本 ...

  4. React多行文本溢出处理(仅针对纯文本)

    最多显示4行,第四行末尾显示“...”

  5. 网易云课堂《JS原创视频教程-知识点类》

    http://caniuse.com/#index     //Can I use... Support tables for HTML5, CSS3, etc-支持h5和css3的情况列表 JS包含 ...

  6. SpringSecurityOAuth使用JWT Token

    ⒈JWT? JWT(Json Web Token),是Json的一个开放的Token标准. 1,自包含,SpringSecurityOAuth的默认Token是UUID的一个随机的无意义的字符串,并不 ...

  7. 积分从入门到放弃<2>

    这部分重新从定积分学了 1,lnx 的导数就是x^(-1) = 1/x 那么求∫(1/x)dx = ln|x|+C  2,初值问题.就是求∫f(x)dx = F(x) + C 求C . 3,Houdi ...

  8. Linux嗅探ettercap

    场景 拿到一台C段的Linux服务器,对目标主机进行嗅探 ettercap安装 操作环境 Centos 6 $ sudo yum install -y libtool-ltdl ncurses-dev ...

  9. Django:前后端分离后联调给前端传数据

    实现前后端分离后,有了下面几点改变: 1.服务器一分为二,前后端分别部署,静态资源放在前端服务器,业务代码放在后的服务器 2.前端服务器需要接收Http请求(一般使用node.js) 3.前端服务器需 ...

  10. codeforces411div.2

    每日CF: 411div2 Solved A CodeForces 805A Fake NP Solved B CodeForces 805B 3-palindrome Solved C CodeFo ...