Python爬虫系列之一:爬取糗事百科段子(24小时)

场景
  • 没有爬数据的能力,更谈不上做好数据分析!
  • 网上虽有很多文档参考,但一直感觉:纸上得来终觉浅!
  • 啊哈, 有点儿假文艺了。其实最大的痛就是,毕竟网上的都是别(zi)人(ji)家(tai)的(cai)文档;通过总结,一方面希望积累知识,另一方面希望有所帮助。

描述
  • 基于 Python 爬取 糗事百科段子 数据。

代码
  • 1 主要部分
import re
import urllib
import bs4
import pandas as pd
from bs4 import BeautifulSoup

page = 1 # 第 1 页

url = 'http://www.qiushibaike.com/hot/page/' + str(page)
header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3236.0 Safari/537.36'}
request = urllib.request.Request(url,headers=header)
response = urllib.request.urlopen(request).read()

content=BeautifulSoup(response, 'lxml')

'''
1 获取段子内容
'''
divs = content.find_all('div', class_='content')
content_lis=[]
for div in divs:
    content_lis.append(div.span.get_text())

'''
2 获取用户昵称
''' 
tmp=content.find_all('div', class_='col1')[0]
nick_name_lis=[]
for nick_name in tmp.find_all('h2'):
    nick_name_lis.append(nick_name.get_text())

'''
3 获取好笑、评论数量
'''
counter=0
funny_lis=[]
comment_lis=[]
for cofu in content.find_all('i', class_='number'):
    counter+=1
    if counter%2!=0:
        funny_lis.append(cofu.get_text())
    else :
        comment_lis.append(cofu.get_text())  

'''
4 打印当前页
'''
current_page=content.find_all('ul',class_='pagination')[0].find_all('span',class_='current')[0].get_text()
print ('\033[1;31m[24H] current page:\033[0m \033[0;30;43m%s\033[0m' % (current_page.replace('\n','')))

'''
5 转换为 DF并显示
'''
tdf=pd.DataFrame([nick_name_lis,content_lis,funny_lis,comment_lis])
df=tdf.T
df.columns=['nick_name','content','funny_cnt','comment_cnt']
df.head(3)
  • 数据效果

格式化效果


  • 2 格式调整
pd.set_option('display.width',200)
pd.set_option('display.max_columns',20)
pd.set_option('display.max_rows',50)
pd.set_option('display.max_colwidth',200)
  • 调整效果

modify


工具
  • Anaconda 3.Jupyter NoteBook
  • Python 3

参考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xsimah

创作不易,感谢客官的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值