Python 制作糗事百科爬虫实例

yipeiwu_com6年前Python爬虫

早上起来闲来无事做,莫名其妙的就弹出了糗事百科的段子,转念一想既然你送上门来,那我就写个爬虫到你网站上爬一爬吧,一来当做练练手,二来也算找点乐子。

其实这两天也正在接触数据库的内容,可以将爬取下来的数据保存在数据库中,以待以后的利用。好了,废话不多说了,先来看看程序爬取的数据结果

值得一提的是,我在程序中想一下子爬取糗事百科 30 页的内容,但是出现了连接错误,当我把页数降到 20 页的时候,程序就可以正常的跑起来了,不知道是什么原因,渴望知道的大神可以告诉我一声,感激不尽。

程序非常简单,直接上源代码咯

# coding=utf8

import re
import requests
from lxml import etree
from multiprocessing.dummy import Pool as ThreadPool
import sys

reload(sys)
sys.setdefaultencoding('utf-8')


def getnewpage(url, total):
 nowpage = int(re.search('(\d+)', url, re.S).group(1))
 urls = []

 for i in range(nowpage, total + 1):
  link = re.sub('(\d+)', '%s' % i, url, re.S)
  urls.append(link)

 return urls


def spider(url):
 html = requests.get(url)
 selector = etree.HTML(html.text)

 author = selector.xpath('//*[@id="content-left"]/div/div[1]/a[2]/@title')
 content = selector.xpath('//*[@id="content-left"]/div/div[2]/text()')
 vote = selector.xpath('//*[@id="content-left"]/div/div[3]/span/i/text()')

 length = len(author)
 for i in range(0, length):
  f.writelines('作者 : ' + author[i] + '\n')
  f.writelines('内容 :' + str(content[i]).replace('\n','') + '\n')
  f.writelines('支持 : ' + vote[i] + '\n\n')


if __name__ == '__main__':

 f = open('info.txt', 'a')
 url = 'http://www.qiushibaike.com/text/page/1/'
 urls = getnewpage(url, 20)

 pool = ThreadPool(4)
 pool.map(spider,urls)
 f.close()

如果其中有不懂得部分,可以依次参考我的前三篇文章。

相关文章

Python爬虫天气预报实例详解(小白入门)

Python爬虫天气预报实例详解(小白入门)

本文研究的主要是Python爬虫天气预报的相关内容,具体介绍如下。 这次要爬的站点是这个:http://www.weather.com.cn/forecast/ 要求是把你所在城市过去...

python爬虫入门教程之糗百图片爬虫代码分享

学习python少不了写爬虫,不仅能以点带面地学习、练习使用python,爬虫本身也是有用且有趣的,大量重复性的下载、统计工作完全可以写一个爬虫程序完成。用python写爬虫需要pytho...

python用BeautifulSoup库简单爬虫实例分析

会用到的功能的简单介绍 1、from bs4 import BeautifulSoup #导入库 2、请求头herders headers={'User-Agent': 'Mo...

python制作最美应用的爬虫

安卓最美应用页面爬虫,爬虫很简单,设计的东西到挺多的 文件操作 正则表达式 字符串替换等等 import requests import re url = "http://zuime...

python 网络爬虫初级实现代码

首先,我们来看一个Python抓取网页的库:urllib或urllib2。 那么urllib与urllib2有什么区别呢? 可以把urllib2当作urllib的扩增,比较明显的优势是u...