美文网首页
python爬取糗事百科

python爬取糗事百科

作者: 奋斗live | 来源:发表于2018-05-09 23:36 被阅读0次

以下使用面向过程版的代码

impore urllib
import urllib2
import re
page = 1
url = 'http://www.qiushibaike.com/hot/page/'+str(page)
#url = 'http://www.yllin.cn'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent':user_agent}
try:
    request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request)
    content = response.read().decode('utf-8')
#print content
    pattern = re.compile('<div class=\"content\"[\s\S]+?<span>([\s\S]+?)<\/span>')
items = re.findall(pattern,content)
    for item in items:
    print item
    except urllib2.URLError, e:
    if hasattr(e,"code"):
    print e.code
    if hasattr(e,"reason"):
    print e.reason

面向对象版

import urllib
import urllib2
import re

class QSBK:
    url ='' 
    headers = ''
    def __init__(self,url,headers):
        self.url = url
        self.headers = headers
    def request(self):
        request = urllib2.Request(url,headers=self.headers)
        response = urllib2.urlopen(request)
        return response
    def decode(self):
        return self.request().read().decode('utf-8')
    
    def solve_data(self):
        pattern = re.compile('<div class=\"content\"[\s\S]+?<span>([\s\S]+?)<\/span>')
        content = self.decode()
        items = re.findall(pattern,content)
        return items
    def print_data(self):
        data = self.solve_data()
        for item in data:
            print item
        

page = 1
url = 'http://www.qiushibaike.com/hot/page/'+str(page)

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent':user_agent}

test = QSBK(url,headers)
test.print_data()

相关文章

  • nice,64个python爬虫入门项目,学会轻轻松松爬取资源

    爬虫在手,资源我有,看完这些,你还敢说你不会爬吗?(滑稽) 1.爬取糗事百科 2.爬取妹子图 3.Python ...

  • python 3  爬糗事百科

    python 3 爬糗事百科(来源Python爬虫学习,实战一糗事百科(2017/7/21更新)) 关于head...

  • 爬虫项目

    64个爬虫项目链接 1.爬取糗事百科 2.爬取妹子图 3.Python 岗位分析报告 4.Selenium介绍 5...

  • Python爬虫实战

    注:采转归档,自己学习查询使用 Python爬虫实战(1):爬取糗事百科段子Python爬虫实战(2):百度贴吧帖...

  • Python爬虫(十七)_糗事百科案例

    糗事百科实例 爬取糗事百科段子,假设页面的URL是: http://www.qiushibaike.com/8hr...

  • Python爬虫教程一爬取糗事百科段子

    这次为大家带来,Python爬取糗事百科的小段子的例子。 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一...

  • Python 学习——每天写点小东西-1

    最近开始学习python,这里就作为学习记录,记录自己的python之路。本条爬虫爬取的是糗事百科的24小时热门里...

  • python爬虫

    1、爬取糗事百科 代码: 2、爬取淘宝手机信息 代码: 3、爬取中国大学排名 代码: 4、爬取豆瓣top250 代码:

  • python爬取糗事百科

    闲来无事,找点段子一乐呵,就逛到糗事百科,这次爬取没有什么难度,唯一值得说道的是增加了一点点的代码健壮性。 其中类...

  • python爬取糗事百科

    以下使用面向过程版的代码 面向对象版

网友评论

      本文标题:python爬取糗事百科

      本文链接:https://www.haomeiwen.com/subject/uusarftx.html