python段子_python爬虫爬取段子

#-*-coding:utf-8

import requests

import os

from bs4 import BeautifulSoup

import lxml

import sys

#改变系统的默认编码

reload(sys)

sys.setdefaultencoding('utf-8')

class DZ():

def __init__(self,url,pageIndex):

self.url=url+str(pageIndex)

self.headers={'User_Agent':'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}

#得到一页的源码

def get_one_page_html(self):

re=requests.get(self.url,self.headers)

html=re.text

return html

#得到所有的段子的url

def get_one_text_url(self):

all_a=[] #这里用来记录每一条段子的链接

for i in range(1,2): #这里先暂时爬取30页的段子

html=self.get_one_page_html()

soup=BeautifulSoup(html,'lxml')

all_h2=soup.find_all('h2')

for h2 in all_h2:

all_a.append(h2.find('a').get('href'))

return all_a

#下载所有的段子

def get_text(self):

all_a=self.get_one_text_url() #首先获得所有段子的url

x=0

for a in all_a:

re=requests.get(a,headers=self.headers)

html=re.text

soup=BeautifulSoup(html,'lxml')

all_p=soup.find('article',class_='article-content').find_all('p')

for p in all_p:

print p.text

if __name__=='__main__':

url='https://duanziwang.com/category/duanzi/page/'

app=DZ(url,1)

app.get_text()

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值