【发布时间】:2013-01-17 03:07:00
【问题描述】:
我想从this site 中抓取以下三个数据点:%verified、FAR 的数值和 POD 的数值。我试图在 BeautifulSoup 中做到这一点,但我没有在站点遍历方面练习过,所以我无法描述这些元素的位置。
最简单的方法是什么?
【问题讨论】:
标签: python web-scraping screen-scraping beautifulsoup
我想从this site 中抓取以下三个数据点:%verified、FAR 的数值和 POD 的数值。我试图在 BeautifulSoup 中做到这一点,但我没有在站点遍历方面练习过,所以我无法描述这些元素的位置。
最简单的方法是什么?
【问题讨论】:
标签: python web-scraping screen-scraping beautifulsoup
如果您还没有,请为 Firefox 安装 Firebug 并使用它来检查页面的 html 源代码。
使用urllib 和BeautifulSoup 的组合来处理html 检索和解析。这是一个简短的例子:
import urllib
from BeautifulSoup import BeautifulSoup
url = 'http://mesonet.agron.iastate.edu/cow/?syear=2009&smonth=9&sday=12&shour=12&eyear=2012&emonth=9&eday=12&ehour=12&wfo=ABQ&wtype[]=TO&hail=1.00&lsrbuffer=15<ype[]=T&wind=58'
fp = urllib.urlopen(url).read()
soup = BeautifulSoup(fp)
print soup
从这里开始,我提供的链接应该让您开始了解如何检索您感兴趣的元素。
【讨论】:
就像 That1Guy 所说的,您需要分析源页面结构。在这种情况下,您很幸运...您正在查看的数字使用<span> 以红色特别突出显示。
这将执行此操作:
>>> import urllib2
>>> import lxml.html
>>> url = ... # put your URL here
>>> html = urllib2.urlopen(url)
>>> soup = lxml.html.soupparser.fromstring(html)
>>> elements = soup.xpath('//th/span')
>>> print float(elements[0].text) # FAR
0.67
>>> print float(elements[1].text) # POD
0.58
注意lxml.html.soupparser 几乎等同于BeautifulSoup 解析器(我现在不需要处理)。
【讨论】:
我最终自己解决了这个问题——我正在使用类似于 isedev 的策略,但我希望我能找到一种更好的方法来获取“已验证”数据:
import urllib2
from bs4 import BeautifulSoup
wfo = list()
def main():
wfo = [i.strip() for i in open('C:\Python27\wfo.txt') if i[:-1]]
soup = BeautifulSoup(urllib2.urlopen('http://mesonet.agron.iastate.edu/cow/?syear=2009&smonth=9&sday=12&shour=12&eyear=2012&emonth=9&eday=12&ehour=12&wfo=ABQ&wtype%5B%5D=TO&hail=1.00&lsrbuffer=15<ype%5B%5D=T&wind=58').read())
elements = soup.find_all("span")
find_verify = soup.find_all('th')
far= float(elements[1].text)
pod= float(elements[2].text)
verified = (find_verify[13].text[:-1])
【讨论】: