【发布时间】:2011-10-27 19:49:45
【问题描述】:
我的项目概述:
我正在尝试在 python 2.6 中创建一个简单的脚本,该脚本将从 Bing Maps 获取交通时间数据。 Scrapy 库模块包 (scrapy.org/) 是我用来爬取每个网站并从 Bing 地图中提取数据的工具。
上面的图片显示了我想要的。 (现在突出显示的数据部分,但最终也需要下面的时间。)
我首先做了一个测试,看看启动 url 是否会出现。如果成功通过,然后使用输出日志打印 url 的输出。一旦成功,我的下一步就是尝试从网页中提取我需要的数据。
我一直在使用 Firebug、XPather 和 XPath Firefox Add-ons 来查找我想要提取的数据的 html 路径。该链接在指导我正确编码路径(doc.scrapy.org/topics/selectors.html)方面非常有帮助。从看萤火虫,这就是我想要提取的......
<span class="time">22 min</span>
XPather 将其显示为该特定项目的路径。 ...
/div[@id='TaskHost_DrivingDirectionsSummaryContainer']/div[1]/span[3]
当我使用上面给定的路径在 cmd 中运行程序时,提取的数据打印为 [ ] 并且当我将 /class='time' 添加到 span 的末尾时,打印输出的数据为 [u'False' ]。在 firebug 的 DOM 窗口中仔细观察时,我注意到 class="time" 对于获取 isID 是错误的,并且 childNode 保存了我需要的数据。如何从 childNode 中提取数据?
下面是我目前的代码
from scrapy import log # This module is useful for printing out debug information
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector, XPathSelectorList, XmlXPathSelector
import html5lib
class BingSpider(BaseSpider):
name = 'bing.com/maps'
allowed_domains = ["bing.com/maps"]
start_urls = [
"http://www.bing.com/maps/?FORM=Z9LH4#Y3A9NDAuNjM2MDAxNTg1OTk5OTh+LTc0LjkxMTAwMzExMiZsdmw9OCZzdHk9ciZydHA9cG9zLjQwLjcxNDU0OF8tNzQuMDA3MTI1X05ldyUyMFlvcmslMkMlMjBOWV9fX2VffnBvcy40MC43MzE5N18tNzQuMTc0MTg1MDAwMDAwMDRfTmV3YXJrJTJDJTIwTkpfX19lXyZtb2RlPUQmcnRvcD0wfjB+MH4="
]
def parse(self, response):
self.log('A response from %s just arrived!' % response.url)
x = HtmlXPathSelector(response)
time=x.select("//div[@id='TaskHost_DrivingDirectionsSummaryContainer']/div[1]/span[3]").extract()
print time
CMD 输出
2011-09-05 17:43:01-0400 [scrapy] DEBUG: Enabled item pipelines:
2011-09-05 17:43:01-0400 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:602
3
2011-09-05 17:43:01-0400 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2011-09-05 17:43:01-0400 [bing.com] INFO: Spider opened
2011-09-05 17:43:02-0400 [bing.com] DEBUG: Crawled (200) <GET http://www.bing.co
m/maps/#Y3A9NDAuNzIzMjYwOTYzMTUwMDl+LTc0LjA5MDY1NSZsdmw9MTImc3R5PXImcnRwPXBvcy40
MC43MzE5N18tNzQuMTc0MTg1X05ld2FyayUyQyUyME5KX19fZV9+cG9zLjQwLjcxNDU0OF8tNzQuMDA3
MTI0OTk5OTk5OTdfTmV3JTIwWW9yayUyQyUyME5ZX19fZV8mbW9kZT1EJnJ0b3A9MH4wfjB+> (refer
er: None)
2011-09-05 17:43:02-0400 [bing.com] DEBUG: A response from http://www.bing.com/m
aps/ just arrived!
[]
2011-09-05 17:43:02-0400 [bing.com] INFO: Closing spider (finished)
2011-09-05 17:43:02-0400 [bing.com] INFO: Spider closed (finished)
【问题讨论】:
-
是否需要使用scrapy库?使用正则表达式编写自定义代码以提取数据。
-
我想我应该提到我对 html 代码知之甚少(更不用说我的编程知识很差,因为大学里的 CS 老师很糟糕。)我只是在处理来自的文件scrapy 从 w3schools 开始学习一些关于 html 和 XPath 的知识。
-
我遇到过几次,网站会根据您的浏览器返回不同的 html。当您在浏览器中测试 xpath 查询以及通过 scrapy(或 curl 或其他方式)下载它时,只需检查返回的正文是否相同。
-
//div[@id='TaskHost_DrivingDirectionsSummaryContainer']//span[@class='time']/text()试试这个 -
还有
allowed_domains = ["bing.com/maps"]我认为应该是allowed_domains = ["bing.com"],因为域名实际上是bing.com
标签: python xpath firebug bing-maps scrapy