出现的问题以及解决方法。
1、爬下来的网页中文乱码:
解决方法:引入chardet包. (百度chardet到官网并且下载,之后解压缩,然后把整个文件夹拷贝到项目文件夹; 或者我的ide – pycharm写入一行import chardet 之后检测没有之后会自动下载)
#从url读取信息
request=urllib2.Request(url,headers=headers)
response = urllib2.urlopen(request)
content=response.read()
htmlChardetGuess=chardet.detect(content)
htmlChardetEncoding=htmlChardetGuess["encoding"]
#解码
contentDecode=content.decode(htmlChardetEncoding)
#获取系统编码
currentSystemEncoding=sys.getfilesystemencoding()
#再编码
content=content.encode(currentSystemEncoding)
print content
2、之后我的ide还是报了一个错说ascii码解码错误,貌似这是因为python自己的事情
解决方法:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
3、下面讲一下爬微博的粉丝的方法。由于只是公司的临时需求,只是粗浅的学习了一点python.
首先打开微博,查看一下微博html文件样式。
然后我们大致的看一下我们所需要的信息在哪里,上下文情况,然后根据这些写出来我们的正则表达式.
userNameAndIconPatter=re.compile('<a target="_blank" title="(.*?)" href=.*?">.*?'
'<img.*?src="(.*?)">.*?<div class="info_name W_fb W_f14">.*?<i class="W_icon (.*?)"></i>',re.S)
有了正则表达式之后,我们就可以遍历html文件,然后取得所需要的信息,并且根据需求。我保存到了list里,最后导出到excel文件了。
import re
import urllib2
import urllib
import sys
import chardet
import xlwt
#due to the encoding of the project
reload(sys)
sys.setdefaultencoding('utf-8')
UserCount=1;
UserInfoList=[]
loop=1;
while loop<=50:
#open a html file
content=open('htmlFile/'+str(loop)+'.txt').read( )
ChardetGuess=chardet.detect(content)
ChardetEncoding=ChardetGuess["encoding"]
contentDecode=content.decode(ChardetEncoding)
currentSystemEncoding=sys.getfilesystemencoding()
content=content.encode(currentSystemEncoding)
#####print content
#read user name and icon info
userNameAndIconPatter=re.compile('<a target="_blank" title="(.*?)" href=.*?">.*?'
'<img.*?src="(.*?)">.*?<div class="info_name W_fb W_f14">.*?<i class="W_icon (.*?)"></i>',re.S)
userNameAndIconItems=re.findall(userNameAndIconPatter,content)
for userNameAndIconItem in userNameAndIconItems:
tempArr=[]
print userNameAndIconItem[0],\
userNameAndIconItem[1],\
userNameAndIconItem[2]
print("\n")
#add user info into the tempUserInfoList
#userName
tempArr.append(userNameAndIconItem[0])
#usergender
if userNameAndIconItem[2].__eq__('icon_male'):
tempArr.append('male')
else:
tempArr.append('female')
#userIcon
tempArr.append(str(UserCount)+'.jpg')
#add tempUserInfoList into UserInfoList
UserInfoList.append(tempArr)
#download pics
url=userNameAndIconItem[1]
urllib.urlretrieve(url,'E://sina_user_icons/'+str(UserCount)+'.jpg')
UserCount+=1;
loop+=1;
#show all info in the memory
for item in UserInfoList:
print item[0],\
item[1],\
item[2],
print("\n")
#save in the excel file
book=xlwt.Workbook(encoding='utf-8',style_compression=0)
sheet=book.add_sheet('sina_user_info',cell_overwrite_ok=False)
sheet.write(0,0,'fuck')