python 开心网和豆瓣日记爬取的小爬虫


Posted in Python onMay 29, 2021

项目地址:

https://github.com/aturret/python-crawler-exercise

用到了BeautifulSoup4,请先安装。

pip install beautifulsoup4

开心网日记爬取

kaixin001.py

使用

登录开心网,浏览器F12看http请求的header,获取自己的cookie。

填写cookie,要爬的日记的url,要爬的总次数。走你。

之后会生成HTML文件,格式是<:title>-<YYYYMMDDHHMMSS>

代码

# -*- coding: utf-8 -*-
from urllib.request import urlopen
import urllib.request
import urllib.parse #为了获取HTTP response
from bs4 import BeautifulSoup #BS4
import string # 为了去掉空白字符
import time # 防止被杀cookie
import unicodedata # 字符修正
# 在这里放第一个链接
urlx = '链接' #写你想爬的文

def request(url):
    global urlx #引用外面的链接作为全局变量,后面还会取下一个进行循环的


# 使用urllib库提交cookie获取http响应
    headers = {
    'GET https':url,
    'Host':' www.kaixin001.com',
    'Connection':' keep-alive',
    'Upgrade-Insecure-Requests':' 1',
    'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
    'Accept':' application/json, text/javascript, */*; q=0.01',
    'Accept-Language':' zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cookie':' ', #改成自己的cookie,自己浏览器打开网站F12调试,自己找http请求的header
    }
    request = urllib.request.Request(url=url,headers=headers)
    response = urllib.request.urlopen(request)
    contents = response.read()

# 使用BS4获得所有HTMLtag
    bsObj = BeautifulSoup(contents,"html.parser")

# 使用BS4的find函数得到想要的东西:标题、发表时间和博客正文
    title = bsObj.find("b", attrs={"class":"f14"})
    titleT = bsObj.find("b", attrs={"class":"f14"}).get_text() #开心网日记的标题是一个b标签,class属性值是f14
    date = bsObj.find("span", attrs={"class":"c6"})
    dateT = bsObj.find("span", attrs={"class":"c6"}).get_text() #开心网日记的发表时间是一个span标签,class属性值是c6
    text = bsObj.find("div", attrs={"class":"textCont"})
    textT = bsObj.find("div", attrs={"class":"textCont"}).get_text() #开心网日记的正文是一个div标签,class属性值是textCont

  

# 测试输出
    print(title)
    print(dateT)
    # print(text)
    
    
    

# 生成HTML文件。这里直接用file.open()和file.write()了,也可以用jinja2之类的框架生成。
    remove = string.whitespace+string.punctuation
    table = str.maketrans(':',':',remove)

    fileTitle=str(titleT).replace(':',':').replace('''"''','''“''')+'-'+str(dateT).translate(table).replace('发表','')+'.html'

    print(fileTitle) #测试输出

    f = open(fileTitle,'w',encoding="utf-8") #注意用utf-8编码写入,不然会因为一些旧博文采用的gbk编码不兼容而出问题。

# 写入message
    message = """
    <html>
    <head></head>
    <body>
    <h1>%s</h1>
    <b>%s</b>
    <br></br>
    %s
    </body>
    </html>"""%(title.get_text(),date.get_text(),unicodedata.normalize('NFD',text.prettify()))
    f.write(message)
    f.close()
    # webbrowser.open(fileTitle,new = 1)
   

# 定位下一篇博文的URL

    nextUrl=bsObj.find("a",text="下一篇 >").attrs["href"] #下一篇是一个a标签,使用tag对象的attrs属性取href属性的值。开心网的日记系统里,如果到了最后一篇日记,下一篇的链接内容是第一篇日记,所以不用担心从哪篇日记开始爬。
    # print(nextUrl)
    urlx="http://www.kaixin001.com"+nextUrl
    print(urlx)


# 主循环,给爷爬
num=328 #设定要爬多少次。其实也可以写个数组检测重复然后中止的啦,但我懒得弄了。
for a in range(num):
    request(urlx)    
    print('We get '+str(a+1)+' in '+str(num))
    time.sleep(1) # 慢点,慢点。测试过程中出现了没有设置限制爬一半cookie失效了的情况,可能是太快了被搞了。

豆瓣日记爬取

douban.py

使用

登录豆瓣,浏览器F12看http请求的header,获取自己的cookie。

填写变量COOKIE,要爬的日记页的url。走你。

之后会生成HTML文件,格式是<:title>-<YYYYMMDDHHMMSS>

代码

# -*- coding: utf-8 -*-
from urllib.request import urlopen
import urllib.request
import urllib.parse #为了获取HTTP response
from bs4 import BeautifulSoup #BS4
import string # 为了去掉空白字符
import unicodedata # 字符修正
import re
# 在这里放链接
url = '' #写你想爬的人 https://www.douban.com/people/xxx/notes 这样
COOKIE = ''

def request(urlx):
    global url #引用外面的链接作为全局变量,后面还会取下一个进行循环的
    global boolean
    global COOKIE
# 使用urllib库提交cookie获取http响应
    headers = {
    'GET https':urlx,
    'Host':' www.douban.com',
    'Connection':' keep-alive',
    'Upgrade-Insecure-Requests':' 1',
    'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
    'Accept':' application/json, text/javascript, */*; q=0.01',
    'Accept-Language':' zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cookie':COOKIE, #改成自己的cookie,自己浏览器打开网站F12调试,自己找http请求的header
    }
    request = urllib.request.Request(url=urlx,headers=headers)
    response = urllib.request.urlopen(request)
    contents = response.read()

# 使用BS4获得所有HTMLtag
    bsObj = BeautifulSoup(contents,"html.parser")

# 使用BS4的find函数获取当前页面的所有日记链接
    article = bsObj.find("div", attrs={"class":"article"})
    titleSet = article.findAll("h3")
    # print(titleSet)
    for title in titleSet:
        titleText = title.findAll("a",attrs={"class":"j a_unfolder_n"})
        for link in titleText:
            noteUrl = str(link.attrs["href"])
            print(noteUrl)
            requestSinglePage(noteUrl)
    next = bsObj.find("a",text="后页>")
    if next==None:
        print("结束了")
        boolean=1
    else:
        url = str(next.attrs["href"]).replace("&type=note","")
        print(url)

def requestSinglePage(urly):
    global COOKIE
    headers = {
        'GET https':urly,
        'Host':' www.douban.com',
        'Connection':' keep-alive',
        'Upgrade-Insecure-Requests':' 1',
        'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
        'Accept':' application/json, text/javascript, */*; q=0.01',
        'Accept-Language':' zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Cookie':COOKIE, #改成自己的cookie,自己浏览器打开网站F12调试,自己找http请求的header
    }
    request = urllib.request.Request(url=urly,headers=headers)
    response = urllib.request.urlopen(request)
    contents = response.read()
    # 使用BS4获得所有HTMLtag
    bsObj = BeautifulSoup(contents,"html.parser")

# 使用BS4的find函数得到想要的东西:标题、发表时间和博客正文

    title = bsObj.find("h1").get_text()
    date = bsObj.find("span", attrs={"class":"pub-date"})
    dateT = bsObj.find("span", attrs={"class":"pub-date"}).get_text()
    text = bsObj.find("div", attrs={"id":"link-report"})
    # textT = bsObj.find("div", attrs={"class":"textCont"}).get_text()

# 测试输出
    print(title)
    print(dateT)

    # 生成HTML文件。这里直接用file.open()和file.write()了,也可以用jinja2之类的框架生成。
    remove = string.whitespace+string.punctuation # 去掉日期的标点符号
    table = str.maketrans(':',':',remove)

    fileTitle=str(title)+'-'+str(dateT).translate(table)+'.html'

    print(fileTitle) #测试输出

    f = open(fileTitle,'w',encoding="utf-8") #注意用utf-8编码写入,不然会因为一些旧博文采用的gbk编码不兼容而出问题。

    # 写入message
    message = """
    <html>
    <head></head>
    <body>
    <h1>%s</h1>
    <b>%s</b>
    <br></br>
    %s
    </body>
    </html>"""%(title,dateT,unicodedata.normalize('NFD',text.prettify()))
    f.write(message)
    f.close()

# 主循环,给爷爬

boolean=0
while(boolean==0):
    a=1
    request(url)
    print('We finished page '+str(a)+' .')
    a+=1

Roadmap

豆瓣四月份时候还有bug,手机端可以看到全部日记,半年隐藏无效。最近修好了。

不过现在的隐藏依然没有针对到具体的日记,或许可以想办法通过其他手段爬下来。

以上就是python 开心网日记爬取的示例步骤的详细内容,更多关于python 开心网日记爬取的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
初步介绍Python中的pydoc模块和distutils模块
Apr 13 Python
Python解析nginx日志文件
May 11 Python
python 禁止函数修改列表的实现方法
Aug 03 Python
浅谈Python Opencv中gamma变换的使用详解
Apr 02 Python
Django使用详解:ORM 的反向查找(related_name)
May 30 Python
Python OpenCV处理图像之图像像素点操作
Jul 10 Python
python爱心表白 每天都是浪漫七夕!
Aug 18 Python
Pycharm运行加载文本出现错误的解决方法
Jun 27 Python
python实现银行管理系统
Oct 25 Python
pandas 像SQL一样使用WHERE IN查询条件说明
Jun 05 Python
使用PyCharm安装pytest及requests的问题
Jul 31 Python
用python计算文件的MD5值
Dec 23 Python
Python趣味挑战之实现简易版音乐播放器
新手必备Python开发环境搭建教程
Keras多线程机制与flask多线程冲突的解决方案
May 28 #Python
pytorch 6 batch_train 批训练操作
May 28 #Python
pytorch 如何使用batch训练lstm网络
May 28 #Python
使用Pytorch训练two-head网络的操作
May 28 #Python
使用Python的开发框架Brownie部署以太坊智能合约
You might like
php实现redis数据库指定库号迁移的方法
2015/01/14 PHP
PHP获取路径和目录的方法总结【必看篇】
2017/03/04 PHP
基于Web标准的UI组件 — 树状菜单(2)
2006/09/18 Javascript
Javascript实例教程(19) 使用HoTMetal(5)
2006/12/23 Javascript
jQuery的实现原理的模拟代码 -4 重要的扩展函数 extend
2010/08/03 Javascript
非常有用的40款jQuery 插件推荐(系列二)
2011/12/25 Javascript
dwz 如何去掉ajaxloading具体代码
2013/05/22 Javascript
基于jQuery实现表单提交验证
2014/11/24 Javascript
jQuery实现的简洁下拉菜单导航效果代码
2015/08/26 Javascript
js控制文本框只能输入中文、英文、数字与指定特殊符号的实现代码
2016/09/09 Javascript
angular中使用Socket.io实例代码
2017/06/03 Javascript
create-react-app修改为多页面支持的方法
2018/05/17 Javascript
深入浅析javascript函数中with
2018/10/28 Javascript
vue实现的树形结构加多选框示例
2019/02/02 Javascript
在vue中获取微信支付code及code被占用问题的解决方法
2019/04/16 Javascript
JS实现音乐导航特效
2020/01/06 Javascript
[56:57]LGD vs VP 2019DOTA2国际邀请赛淘汰赛 胜者组赛BO3 第一场 8.20.mp4
2019/08/22 DOTA
高性能web服务器框架Tornado简单实现restful接口及开发实例
2014/07/16 Python
Python访问MySQL封装的常用类实例
2014/11/11 Python
linux平台使用Python制作BT种子并获取BT种子信息的方法
2017/01/20 Python
Python中的TCP socket写法示例
2018/05/11 Python
一个可以套路别人的python小程序实例代码
2019/04/09 Python
python 读写excel文件操作示例【附源码下载】
2019/06/19 Python
基于 HTML5 WebGL 实现的垃圾分类系统
2019/10/08 HTML / CSS
如何用H5实现一个触屏版的轮播器的实例
2017/01/09 HTML / CSS
Trench London官方网站:高级风衣和意大利皮夹克
2020/07/11 全球购物
装潢设计专业推荐信模板
2013/11/26 职场文书
2014年会策划方案
2014/05/11 职场文书
银行员工考核评语
2014/12/31 职场文书
关于清明节的演讲稿2015
2015/03/18 职场文书
2016廉洁从政心得体会
2016/01/19 职场文书
世界上超棒的8种逻辑思维
2019/08/06 职场文书
PHP 对接美团大众点评团购券(门票)的开发步骤
2021/04/03 PHP
Springboot如何使用logback实现多环境配置?
2021/06/16 Java/Android
golang 语言中错误处理机制
2021/08/30 Golang
SQL Server中搜索特定的对象
2022/05/25 SQL Server