分享

用Python 写网络爬虫

 youxd 2016-12-27

CodeSnippet 抓取代码片段

目标

抓取CodeSnippet中的代码片段

用Python 写网络爬虫-第一个网络爬虫

代码片段

分析

用Python 写网络爬虫-第一个网络爬虫

DOM结构

我们想要抓取的内容在为

li class='con-code bbor' 所以 BeautifulSoup find()方法获取到该标签然后获取其文本内容

准备

准备我们爬虫比用的两个模块

from urllib2 import urlopenfrom bs4 import BeautifulSoup

编写抓取代码

# 抓取http://www./index.html 中的代码片段def GrapIndex(): html = 'http://www./index.html' bsObj = BeautifulSoup(urlopen(html), 'html.parser') return bsObj.find('li', {'class':'con-code bbor'}).get_text()

当我们抓取到我们想要的数据之后接下来要做的就是把数据写到数据库里,由于我们现在抓取数据简单,所以只写文件即可!

def SaveResult(): codeFile=open('code.txt', 'a') # 追加 for list in GrapIndex(): codeFile.write(list) codeFile.close()

当我们在写文件的时候出现了以下错误,而下面这个错误的造成原因则是由于python2.7是基于ascii去处理字符流,当字符流不属于ascii范围内,就会抛出异常(ordinal not in range(128))

UnicodeEncodeError: 'ascii' codec can't encode character u'u751f' in position 0: ordinal not in range(128)

分析

python2.7是基于ascii去处理字符流,当字符流不属于ascii范围内,就会抛出异常(ordinal not in range(128))

解决办法

import sysreload(sys)sys.setdefaultencoding('utf-8')

完整代码展示

from urllib2 import urlopenfrom bs4 import BeautifulSoupimport osimport sysreload(sys)sys.setdefaultencoding('utf-8')def GrapIndex(): html = 'http://www./index.html' bsObj = BeautifulSoup(urlopen(html), 'html.parser') return bsObj.find('li', {'class':'con-code bbor'}).get_text()def SaveResult(): codeFile=open('code.txt', 'a') for list in GrapIndex(): codeFile.write(list) codeFile.close() if __name__ == '__main__': for i in range(0,9): SaveResult()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多