学习网络爬虫的第二个程序:
#-*- coding:utf-8 -*-
#import re
import urllib
from bs4 import BeautifulSoup
import urlparse #处理url链接的库
import chardet #字符集检测
import sys #解决UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-15: ordinal not in range(128)
reload(sys)
sys.setdefaultencoding( "utf-8" )
"""
爬取某贴吧第一页的所有帖子的标题、连接、作者,将数据储存到txt文件中
"""
def get_content(url):
""" 获取页面源码"""
html = urllib.urlopen(url) #获取网站页面的地址
content = html.read() #将页面读取到content变量中
html.close() #关闭页面
#local = '/root/desktop/python/teiba.html'
#urllib.urlretrieve(url,local) #将页面源码下载的本地
#print chardet.detect(content) #检测网页的字符集,依据网页具体内容
return content
def get_author(info):
"""
提取帖子里面的作者
"""
soup = BeautifulSoup(info) #转换成soup对象
all_author = soup.find_all('