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爬虫实现爬取京东手机页面的图片(实例代码)

实例如下所示: __author__ = 'Fred Zhao' import requests from bs4 import BeautifulSoup import os...

Python爬取数据并写入MySQL数据库的实例

Python爬取数据并写入MySQL数据库的实例

首先我们来爬取 http://html-color-codes.info/color-names/ 的一些数据。 按 F12 或 ctrl+u 审查元素,结果如下: 结构很清晰简单,...

33个Python爬虫项目实战(推荐)

今天为大家整理了32个Python爬虫项目。 整理的原因是,爬虫入门简单快速,也非常适合新入门的小伙伴培养信心。所有链接指向GitHub,祝大家玩的愉快~O(∩_∩)O WechatS...

一些常用的Python爬虫技巧汇总

Python爬虫:一些常用的爬虫技巧总结 爬虫在开发过程中也有很多复用的过程,这里总结一下,以后也能省些事情。 1、基本抓取网页 get方法 import urllib2 url...

Python爬虫之urllib基础用法教程

综述 本系列文档用于对Python爬虫技术进行简单的教程讲解,巩固自己技术知识的同时,万一一不小心又正好对你有用那就更好了。 Python 版本是3.7.4 urllib库介绍 它是...