BeautifulSoup实战
来源:互联网 发布:江苏银河网络 编辑:程序博客网 时间:2024/06/05 09:15
最近我的博客主要都在自己的网站上写,所以在CSDN上很少更新,希望各位读者光临我的站点http://a2bgeek.me
最近有个项目要用天气数据,看了一些天气网站,决定从中国天气网
上抓数据,python
抓数据的框架我知道的不多,只听过BeautifulSoup
,下面记录一下使用BeautifulSoup
抓取数据的全过程。BeautifulSoup
的文档见BeautifulSoup官方文档。
这里大概介绍一下BeautifulSoup
的用法,它和javascript的dom一样,把html文档看做一棵树。
- 可以用下面的代码取得根节点:
1234
from bs4 import BeautifulSoupimport urllibrawdata = urllib.urlopen("http://xxx.xxx.xx")soup = BeautifulSoup(rawdata)
soup
就是根节点了,有了这个根节点就能遍历文档树了。
- find可以快速得到某一个或一簇标签:
1
head = soup.find('head')
可以得到
1234
<head> <title>...<title> <style>...<style></head>
也可以加上id的限制:
1
soup.find(id="link3")
- find_all可以有选择地得到一些标签:
1234
soup.find_all('a')# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
.
也很常用:
12345678
soup.title#可以得到<title>The Dormouse's story</title>soup.title.name#可以得到标签名soup.title.string#可以得到标签之间的文本soup.p['class']#可以得到p标签的class属性
- contents也比较常用:
12
soup.body.contents#是一个list,包括了body的所有子节点,既有tag也有文本。
下面介绍抓取中国天气网数据的过程。
首先打开网页兰州天气,再打开firebug找到我们需要抓取的部分。如图所示:,其中id="7d"
的div
就是我们要抓取的部分。下面上代码:
12345678910111213141516171819
tag7d = soup.find(id = "7d")#得到id="7d"的divtagweatherYubaoBox = tag7d.contents[3]#得到class="weatherYubaoBox"的divresultset = [tagweatherYubaoBox.contents[5].find_all("a"), tagweatherYubaoBox.contents[9].find_all("a"), tagweatherYubaoBox.contents[13].find_all("a")]#这里我只想取当天、明天、后天的天气,也就是class="yuBaoTable"的前三个table,接下来就可以循环去数据了。result = []for item in resultset: tmp_dict = {} tmp_dict["date"] = item[0].string tmp_dict["imgurl"] = ''.join(["http://www.weather.com.cn", item[1].contents[1]["src"]]) tmp_dict["weather"] = item[2].string if len(item) == 6:#中国天气网的数据在6点以后就没有白天的数据了,所以这里判断了一下。 tmp_dict["low"] = ' '.join([u"夜间", item[3].contents[1].contents[0], item[3].contents[1].contents[1].string]) else: tmp_dict["high"] = ' '.join([u"白天", item[3].contents[1].contents[0], item[3].contents[1].contents[1].string]) tmp_dict["low"] = ' '.join([u"夜间", item[8].contents[1].contents[0], item[8].contents[1].contents[1].string]) result.append(tmp_dict)
好了今天就到这里,欢迎拍砖。
1 0
- BeautifulSoup实战
- 实战BeautifulSoup
- Python BeautifulSoup 实战演练
- BeautifulSoup-爬虫实战
- BeautifulSoup
- BeautifulSoup
- BeautifulSoup
- beautifulsoup
- BeautifulSoup
- BeautifulSoup
- BeautifulSoup
- BeautifulSoup
- BeautifulSoup
- beautifulsoup
- BeautifulSoup
- BeautifulSoup
- BeautifulSoup
- BeautifulSoup
- 含软连字符的字符串计算显示长度的问题
- 设计模式学习之——六大设计原则之二:里氏替换原则
- SAP配置webdynpro完全手册
- [LeetCode] Set Matrix Zeroes
- IPv6宽带接入
- BeautifulSoup实战
- C++中的const的内存分配问题
- django apache mod_wsgi配置
- 调用系统距离传感器
- hibernate映射关系
- 不通过服务器控件时用前端javascript与c#后台交互的方法
- STM32的PWM输入模式设置并用DMA接收数据
- 杭电1079
- ip地址192.168.1.1/24