python爬虫教程很多,

本文以爬取博客为例

1.

Beautiful Soup

Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据
为节约篇幅,安装方法自行百度
解析器:

下表列出了主要的解析器,以及它们的优缺点:

解析器 使用方法 优势 劣势
Python标准库 BeautifulSoup(markup,"html.parser")
  • Python的内置标准库
  • 执行速度适中
  • 文档容错能力强
  • Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML 解析器 BeautifulSoup(markup, "lxml")
  • 速度快
  • 文档容错能力强
  • 需要安装C语言库
lxml XML 解析器

BeautifulSoup(markup, ["lxml","xml"])

BeautifulSoup(markup, "xml")

  • 速度快
  • 唯一支持XML的解析器
  • 需要安装C语言库
html5lib BeautifulSoup(markup,"html5lib")
  • 最好的容错性
  • 以浏览器的方式解析文档
  • 生成HTML5格式的文档
  • 速度慢
  • 不依赖外部扩展

推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定.

用法简单介绍:
from bs4 import BeautifulSoupsoup = BeautifulSoup(open("index.html"))
print(soup.prettify())
soup.title
# <title>The Dormouse's story</title>soup.title.name
# u'title'soup.title.string
# u'The Dormouse's story'soup.title.parent.name
# u'head'soup.p
# <p class="title"><b>The Dormouse's story</b></p>soup.p['class']
# u'title'soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
从文档中找到所有<a>标签的链接:
for link in soup.find_all('a'):print(link.get('href'))# http://example.com/elsie# http://example.com/lacie# http://example.com/tillie
从文档中获取所有文字内容:
print(soup.get_text())
# The Dormouse's story
#
说明:这个get_text( )特别好用,因为我要把文章内容提取出来,之前考虑用正则去除哪些网页标签符合,也有用nltk来去除的,后来发现直接可以用这个方法。
2.介绍这么多,下面上我的工程源码
#!/usr/bin/env python
#coding=utf-8
#
#   Copyright 2017 liuxinxing
#from bs4 import BeautifulSoup
import urllib2import datetime
import time
import PyRSS2Gen
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')class RssSpider():def __init__(self):self.myrss = PyRSS2Gen.RSS2(title='OSChina',link='http://my.oschina.net',description=str(datetime.date.today()),pubDate=datetime.datetime.now(),lastBuildDate = datetime.datetime.now(),items=[])self.xmlpath=r'./oschina.xml'self.baseurl="http://www.oschina.net/blog"#if os.path.isfile(self.xmlpath):#os.remove(self.xmlpath)def useragent(self,url):i_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36","Referer": 'http://baidu.com/'}req = urllib2.Request(url, headers=i_headers)html = urllib2.urlopen(req).read()return htmldef enterpage(self,url):pattern = re.compile(r'\d{4}\S\d{2}\S\d{2}\s\d{2}\S\d{2}')rsp=self.useragent(url)# print rspsoup=BeautifulSoup(rsp, "html.parser")# print souptimespan=soup.find('div',{'class':'blog-content'})# print timespantimespan=str(timespan).strip().replace('\n','').decode('utf-8')# match=re.search(r'\d{4}\S\d{2}\S\d{2}\s\d{2}\S\d{2}',timespan)# timestr=str(datetime.date.today())# if match:#     timestr=match.group()#print timestrititle=soup.title.stringprint ititlediv=soup.find('div',{'class':'BlogContent'})# print type(div)doc = div.get_text()# print type(doc)return ititle,docdef getcontent(self):rsp=self.useragent(self.baseurl)# print rspsoup=BeautifulSoup(rsp, "html.parser")# print soupul=soup.find('div',{'id':'topsOfRecommend'})# print ulfor div in ul.findAll('div',{'class':'box-aw'}):# div=li.find('div')# print divif div is not None:alink=div.find('a')if alink is not None:link=alink.get('href')print linkif self.isbloglink(link):title,doc =self.enterpage(link)self.savefile(title,doc)def isbloglink(self,link):express = r".*/blog/.*"mo = re.search(express, link)if mo:return Trueelse:return Falsedef savefile(self,title,doc):doc = doc.decode('utf-8')with open("./data/"+title+".txt",'w') as f:f.write(doc)if __name__=='__main__':rssSpider=RssSpider()rssSpider.getcontent()# rssSpider.enterpage("https://my.oschina.net/diluga/blog/1501203")
文件中还有一些生成rss的东西,可以忽略,因为最开始想做成爬取后生成rss源,后来想直接推送给kindle就没用了。
参考:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

python实现kindle每天推送博客2----python实现爬取博客内容相关推荐

  1. python实现kindle每天推送博客1----kindle推送原理,python实现qq邮箱登录及邮件发送

    kindle想每天看新闻,看博客, 其实自己用python写个代码就能很简单实现了. 1.kindle推送原理 kindle不仅可以买书看书,还可以自己推送内容 原理很简单,往你个人的kindle邮箱 ...

  2. python 爬虫 博客园_Python爬虫爬取博客园作业

    分析一下他们的代码,我在浏览器中对应位置右键,然后点击检查元素,可以找到对应部分的代码.但是,直接查看当前网页的源码发现,里面并没有对应的代码.我猜测这里是根据服务器上的数据动态生成的这部分代码,所以 ...

  3. java获取微信公总号推送的所有信息的url,用于爬取微信推送的文章内容

    场景描述: 在用户提出需要爬取微信公总号推送消息的时候,感觉是懵逼的,之前从来没爬取过,无从下手,没办法顾客是上帝,既然用户提出了需求,我们只能想法去解决问题. 然后根据用户提供微信公总号  安泰科现 ...

  4. python爬虫爬取安居客并进行简单数据分析

    此篇博客为普通方式爬取安居客租房数据一共提取出1200条,但是在进行大规模的数据爬取时,不建议使用这种方式,速度太慢是最大的诟病,在进行大规模爬取时,使用分布式爬虫是第一选择 爬取过程 一.指定爬取数 ...

  5. python websocket实时消息推送

    python websocket实时消息推送 十分想念顺店杂可... 本人写的渣,大神勿喷. 转载请附带本文链接,谢谢. 服务端代码 # -*- coding: utf-8 -*- # @Time : ...

  6. python自动推送消息_使用Python制作自动推送微信消息提醒的备忘录功能

    日常工作生活中,事情一多,就会忘记一些该做未做的事情.即使有时候把事情记录在了小本本上或者手机.电脑端备忘录上,也总会有查看不及时,导致错过的尴尬.如果有一款小工具,可以及时提醒,而不用再主动去查备忘 ...

  7. 批量删除订阅kindle、kindle touch 推送

    多日使用kindle发现推送是个好东西,但是不能在亚马逊的账号中批量删除, javascript:(function(){ var v = new RegExp("PersonalDocum ...

  8. python自动推送消息_用Python设计一个可以自动推送微信消息提醒的备忘录

    请关注微信公众号:金融数学 FinancialMathematics日常工作生活中,事情一多,就会忘记一些该做未做的事情.即使有时候把事情记录在了小本本上或者手机.电脑端备忘录上,也总会有查看不及时, ...

  9. nodejs爬虫与python爬虫_【nodeJS爬虫】前端爬虫系列 -- 小爬「博客园」

    写这篇 blog 其实一开始我是拒绝的,因为爬虫爬的就是cnblog博客园.搞不好编辑看到了就把我的账号给封了:). 言归正传,前端同学可能向来对爬虫不是很感冒,觉得爬虫需要用偏后端的语言,诸如 ph ...

最新文章

  1. 一种注册表沙箱的思路、实现——研究Reactos中注册表函数的实现3
  2. 求点被多少个矩形覆盖
  3. python多核多线程编程_python是否支持多处理器/多核编程?
  4. Swift中的闭包例子
  5. requirejs加载顺序_教你5分钟学会用requirejs(必看篇)
  6. android一格一格向上的进度条,如何 使用 ProgressBar 进度条
  7. 消息中间件 rabbitMQ
  8. 【经典算法】希尔算法
  9. 报表性能优化方案之多种报表服务器内存修改方法
  10. swig: c与其它语言接口文件
  11. 射极跟随器负载加重解析
  12. dnf服务器的ini配置文件,dnf分辨率配置文件在哪 | 手游网游页游攻略大全
  13. 云计算10个入门基础知识
  14. 谷歌浏览器下面的任务栏不见了
  15. 项目时间和本地时间差8小时的问题
  16. 萌新的linux之旅27
  17. minio error occured
  18. iOS开发中Touch ID的使用
  19. 前端canvas画海报
  20. Java web学习文档

热门文章

  1. android 红外驱动,Android内核驱动-红外驱动IR
  2. 微信公众号之底部菜单
  3. 多目标跟踪 TAO 数据集使用方法分享
  4. Android + OpenCV 入门教程笔记(保姆级)
  5. 数论——中国剩余定理
  6. 微信隐藏功能:群接龙
  7. oracle组合单词是什么意思,oracle-bone是什么意思
  8. 没做过项目经理可以考pmp证书吗?普通人考PMP®有用吗?
  9. UI设计中异常状态设计总结
  10. 中国金盐银盐行业研究与投资前景预测报告(2022版)