Python爬虫实战一:爬取糗事百科的文本段子

本文是笔者进行Python爬虫学习自己动手写的第一个完整的程序。实现了最基本的爬虫功能,即对糗事百科里文本段子的爬取,使用字典这一数据结构来存储段子的内容、作者以及点赞数(评论数不知何故,只能输出奇数序号,实现失败),再将其打印输出。

程序主体是两大块:网页下载器、网页解析输出器

初学Python,编程上一定存在着不少的问题,欢迎各路大神拍砖指正。

因笔者是用sublime text3自带的调试器进行程序调试的,该软件调试时不支持交互,故所有常量都是直接赋值的,使用时可以根据实际需要自行修改。

下面贴上代码:

# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import urlparse
import urllib2
import re
import os
import time 


def get_content(urls):
    #网页下载器
	req = urllib2.Request(urls)
	req.add_header("User-agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)")
	response = urllib2.urlopen(req)
	if response.getcode() != 200:
		return None
	return response.read()


def parse(urls, html_cont):
    #网页解析器
	if urls is None or html_cont is None:
		return 
	soup = BeautifulSoup(html_cont, 'html.parser', from_encoding = 'utf-8')
	res_data = {}

	#扒糗事
	'''
	
因为……
''' content_nodes = soup.find_all('div', class_="content") i = 1 for content_node in content_nodes: res_data['content%s'%i] = content_node.get_text().encode('utf-8').strip('\n') i += 1 #扒点赞数 # 7967 thumb_nodes = soup.find_all('span', class_="stats-vote") j = 1 for thumb_node in thumb_nodes: res_data['thumb%s'%j] = thumb_node.get_text().encode('utf-8') j += 1 #扒作者 #
author_nodes = soup.find_all('div', class_="author clearfix") n = 1 for author_node in author_nodes: res_data['author%s'%n] = author_node.get_text().encode('utf-8').strip('\n') n += 1 #扒评论数 # # 10 评论 # ''' comment_nodes = soup.find_all('a', class_="qiushi_comments") m = 1 for comment_node in comment_nodes: res_data['comment%s'%m] = comment_node.get_text().strip('\n') m += 1 ''' k = 1 while (k <= i-1): print "糗事%s:" %k print res_data['content%s'%k] print res_data['thumb%s'%k] # print res_data['comment%s'%k] print "作者:" , print res_data['author%s'%k], print "\n" print "\n" k += 1 # if __name__ == "__main__": pageIndex = 1 maxPage = 10 urls = "http://www.qiushibaike.com/text/page/%s" % pageIndex while (pageIndex <= maxPage): print "#--------------------------#" print "****文字糗事第%s页内容:****" % pageIndex print "#--------------------------#" print "" print "" html_cont = get_content(urls) parse(urls, html_cont) pageIndex += 1 time.sleep(5)

你可能感兴趣的:(Python爬虫实战一:爬取糗事百科的文本段子)