如何用Scrapy爬取黄页

0 投票
1 回答
1909 浏览
提问于 2025-04-18 12:17

我正在尝试从黄页网站抓取数据,但遇到了一个错误,提示“爬虫名称”中没有属性响应。我现在在Linux的Ubuntu系统上,使用的是Python 2.7.3。以下是我的代码:

import scrapy
from scrapy.spider import Spider
from scrapy.http import FormRequest, Request
from scrapy.selector import HtmlXPathSelector

class yellowpages(scrapy.Spider):
    name = 'yellowpages'
    allowed_domains = ['yellowpages.com']
    start_urls = ['http://www.yellowpages.com/whitepages']

def parse(self, response):
  return [FormRequest.from_response(response, headers = None, formdata = {"last name": "lastname person one"}, callback = self.parse_results)]

def parse_results(self, response):
    hxs = HtmlXPathSelector(response)
    print hxs.select('//h3').extract()

补充:

根据要求,我把输出结果放上来了。出于某种原因,现在似乎能够输出页面了。我觉得可能是在我保存代码的时候,它已经在运行了,我需要重启我的终端。现在看起来它输出了一些CSS内容。

     ScrapyDeprecationWarning: Call to deprecated function select. Use .xpath() instead.
  print hxs.select('//h3').extract()
/usr/local/lib/python2.7/dist-packages/scrapy/selector/unified.py:106:       ScrapyDeprecationWarning: scrapy.selector.HtmlXPathSelector is deprecated, instantiate scrapy.Selector instead.
  for x in result]
#CSS Output, removed between terminal and stackoverflow to help with formationg
2014-07-06 15:22:16-0400 [yellowpages] INFO: Closing spider (finished)
2014-07-06 15:22:16-0400 [yellowpages] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 2382,
 'downloader/request_count': 3,
 'downloader/request_method_count/GET': 3,
 'downloader/response_bytes': 40878,
 'downloader/response_count': 3,
 'downloader/response_status_count/200': 2,
 'downloader/response_status_count/301': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2014, 7, 6, 19, 22, 16, 316969),
 'log_count/DEBUG': 5,
 'log_count/INFO': 7,
 'request_depth_max': 1,
 'response_received_count': 2,
 'scheduler/dequeued': 3,
 'scheduler/dequeued/memory': 3,
 'scheduler/enqueued': 3,
 'scheduler/enqueued/memory': 3,
 'start_time': datetime.datetime(2014, 7, 6, 19, 22, 14, 117396)}
2014-07-06 15:22:16-0400 [yellowpages] INFO: Spider closed (finished)

1 个回答

1

最开始,我遇到了一个关于黄页和数据写入表单头部的问题。解决这个问题最简单的方法就是把form_number设置为1。代码如下:

def parse(self, response):
    return [FormRequest.from_response(response, header = None, formnumber = 1, formdata = {"last": "examplename", "state": "examplestate"}, cakkback = self.parse_results)]

接下来的问题是解析数据,我发现最好的方法是通过选择器来处理响应,然后用xpath设置选择器,具体方法如下:

def parse_results(self, response):
    hxs scrapy.Selector(response)
    phone_numbers = hxs.xpath('//p').extract)
    for item in phone_numbers:
            ............

从这里开始,你只需要去掉文本,然后把它写入你需要的任何文档中。

撰写回答