爬虫的简单应用
来源:互联网 发布:网络选修课 编辑:程序博客网 时间:2024/06/03 17:17
这是对 Python网络爬虫与信息提取的一个简单的总结。
在课程中学到的网络爬虫一般分为三个步骤:
网页爬取
这里把给定的url的整个网页代码爬取下来
def getHTMLText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return ''
requests.get()
构造一个向服务器请求资源的request对象,返回一个包含服务器资源的Response对象
r.raise_for_status()
在方法内部判断r.status_code是否等于200,不需要增加额外的if语句,该语句便于利用try‐except进行异常处理
r.encoding=r.apparent_encoding
r.encoding探测到headers里面的charset,要注意这里不是页面上指定的charset
r.apparent_encoding如果headers里面发现不了,则会查找网页内容来探测,不过速度很慢
一般使用这段代码可防止爬取的网页因编码格式乱码
对所需信息进行提取
这里一般用到BeatifulSoup或者正则表达式或两者结合、
BeatifulSoup
举个爬取大学排名的例子中的代码
def fillUnivList(ulist, html): soup = BeautifulSoup(html, 'html.parser') for tr in soup.find('tbody').children: if isinstance(tr, bs4.element.Tag): tds = tr('td') ulist.append([tds[0].contents[0].string, tds[1].string, tds[3].string])
soup = BeautifulSoup(html, ‘html.parser’)
表示对html,以html.parser解析器进行解析,返回的是一个树状结构的对象,它对应着一个HTML/XML文档的全部内容
soup.find(‘tbody’).children
表示将的所有儿子节点存入列表
tds = tr(‘td’)
把tr中所有td标签内容存入列表
.string
表示标签内非属性字符串
正则表达式
以淘宝搜索商品为例:
def parsePage(ilt, html): try: plt = re.findall(r'\"view_price\":\"[\d\.]*\"', html) tlt = re.findall(r'\"raw_title\":\".*?\"', html) for i in range(len(plt)): price = eval(plt[i].split(':')[1]) title = eval(tlt[i].split(':')[1]) ilt.append([price, title]) except: print("")
两者结合
以股票爬取为例:
def getStockList(lst, stockURL): html = getHTMLText(stockURL, "GB2312") soup = BeautifulSoup(html, 'html.parser') a = soup.find_all('a') for i in a: try: href = i.attrs['href'] lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) except: continue
这样就完成了信息的提取,下一步是保存在某个文件还是打印了
代码及结果
大学排名
import requestsfrom bs4 import BeautifulSoupimport bs4def getHTMLText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return ''def fillUnivList(ulist, html): soup = BeautifulSoup(html, 'html.parser') for tr in soup.find('tbody').children: if isinstance(tr, bs4.element.Tag): tds = tr('td') ulist.append([tds[0].contents[0].string, tds[1].string, tds[3].string])def printUnivList(ulist, num): tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}" print(tplt.format("排名","学校名称","总分",chr(12288))) for i in range(num): u=ulist[i] print(tplt.format(u[0],u[1],u[2],chr(12288)))def main(): uinfo = [] url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2017.html' html = getHTMLText(url) fillUnivList(uinfo, html) printUnivList(uinfo, 20) # 20 univsmain()
淘宝搜索
import requestsimport redef getHTMLText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return ""def parsePage(ilt, html): try: plt = re.findall(r'\"view_price\":\"[\d\.]*\"', html) tlt = re.findall(r'\"raw_title\":\".*?\"', html) for i in range(len(plt)): price = eval(plt[i].split(':')[1]) title = eval(tlt[i].split(':')[1]) ilt.append([price, title]) except: print("")def printGoodsList(ilt): tplt = "{:4}\t{:8}\t{:16}" print(tplt.format("序号", "价格", "商品名称")) count = 0 for g in ilt: count = count + 1 print(tplt.format(count, g[0], g[1]))def main(): goods = '书包' depth = 3 start_url = 'https://s.taobao.com/search?q=' + goods infoList = [] for i in range(depth): try: url = start_url + '&s=' + str(44 * i) html = getHTMLText(url) parsePage(infoList, html) except: continue printGoodsList(infoList)main()
阅读全文
0 0
- 爬虫的简单应用
- Python简单爬虫的应用
- WebMagic Java 爬虫的简单应用
- Python3之爬虫中回调函数的简单应用
- 简单的网络爬虫
- 一个简单的爬虫
- 简单的爬虫
- 简单的爬虫程序
- Python简单的爬虫
- 一个简单的爬虫
- 简单的JAVA爬虫
- 简单的python爬虫
- 简单的爬虫入门
- 简单的Python 爬虫
- 简单的爬虫
- 简单的C#爬虫
- java的简单爬虫
- 一个简单的爬虫
- 网络管理
- python爬取数据热点词生成词云
- android studio的一些快捷键
- vscode常用插件
- pandas的read_sql报错UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd3 in position 0: invalid con
- 爬虫的简单应用
- OOA:面向对象
- 字符统计
- BeanFactory not initialized or already closed
- Spring 框架及相关问题记录
- 《Spring实战》学习笔记之一:Spring之旅
- 问题BeanFactory not initialized or already closed
- * 继承与派生 编程题#1(Coursera 程序设计与算法 专项课程3 C++程序设计 郭炜、刘家瑛;OpenJudge)
- LeetCode刷题(13)