利用爬虫把徐小明新浪博客里的所有博文链接爬下来,保存到脚本所在路径的csv文件中(python2.7代码)
把起始博文目录链接换成其他的也是完全可以的
详细内容请关注微信公众号:岛城窝窝,
代码如下
#! /usr/bin/env python
#coding=utf-8
# by huangle63
'''
此代码功能为把徐小明新浪博客的所有博文链接下载保存到本地csv文件中
运行本程序,会在脚本所在路径生成一个 xuxiaoming_blog_catalog.csv 文件
20150419 huangle63
'''
import sys
import re
import csv
import urllib2
from bs4 import BeautifulSoup
#获取页面代码,返回对象是 BeautifulSoup 格式
def get_http_content(url):
try:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
html = urllib2.Request(url, headers = headers)
myResponse = urllib2.urlopen(html)
myPage = myResponse.read()
bsObj = BeautifulSoup(myPage,'html5lib')
return bsObj
except urllib2.URLError as e:
return None
#每个页面链接里有n个博文目录链接
def spider_catalog(spider_href):
no_spider_hrefs.remove(spider_href)
#获取当前页面链接里的博文目录链接
url_content = get_http_content(spider_href)
if url_content == None:
print('ERROR1: Page could not be found')
else:
#获取页面目录信息,格式:日期 标题名 链接
#把获取的信息保存到csv文件中
csvFile = open(sys.path[0] + r'\xuxiaoming_blog_catalog.csv','ab')
try:
for link in url_content.findAll('div',{'class':'articleCell SG_j_linedot1'}):
link_title = link.find('a', href = re.compile("^(http://blog.sina.com.cn/s)")).get_text().replace(u'\u200b','').replace(u'\xa0','')
link_href = link.find('a', href = re.compile("^(http://blog.sina.com.cn/s)")).attrs['href']
link_date = link.find('span',{'class':'atc_tm SG_txtc'}).get_text()
print(link_date + ' ' + link_title + ' ' + link_href)
writer = csv.writer(csvFile)
writer.writerow((link_date,link_title.encode("gbk"),link_href))
except AttributeError as e:#当调用BeautifulSoup对象不存在时,会返回一个NONE对象,如果再调用这个NONE对象下面的子标签,就会发生AttributeError错误
print('ERROR2: BeautifulSoup get the none tag')
finally:
csvFile.close()
#获取当前页面里的其它页面链接(第一页,第二页......)
try:
for link in url_content.find('ul',{'class':'SG_pages'}).findAll('li'):
all_li = link.find('a',href = re.compile("^(http://blog.sina.com.cn/s)"))
if all_li != None:
link_page_href = all_li.attrs['href']
if link_page_href not in page_hrefs:
page_hrefs.add(link_page_href)
no_spider_hrefs.add(link_page_href)
link_page_title = all_li.get_text().replace(u'\u200b','').replace(u'\xa0','')
print(link_page_title + ' ' + link_page_href)
spider_catalog(link_page_href) #递归查询所有页面链接
except AttributeError as e:#当调用BeautifulSoup对象不存在时,会返回一个NONE对象,如果再调用这个NONE对象下面的子标签,就会发生AttributeError错误
print('ERROR2: BeautifulSoup get the none tag')
except Exception as e:
print('ERROR3: ',e)
page_hrefs = set() #pages_href用于去重,把所有链接都存储在pages_hrefs
no_spider_hrefs = set() #用于存储还没有爬虫的页面链接
start_page_html = 'http://blog.sina.com.cn/s/articlelist_1300871220_0_1.html' #起始博文的网页链接
page_hrefs.add(start_page_html)
no_spider_hrefs.add(start_page_html)
spider_catalog(start_page_html)