【问题标题】:Using Scrapy to extract data from Detail Pages使用 Scrapy 从详细信息页面中提取数据
【发布时间】:2013-04-24 14:13:11
【问题描述】:

我正在尝试从该站点抓取代理机构的电话号码:

列表视图 http://www.authoradvance.com/agencies/

详细视图 http://www.authoradvance.com/agencies/b-personal-management/

电话号码隐藏在详细信息页面中。

那么是否可以通过像上面的详细视图 url 这样的 url 浏览网站并抓取电话号码?

我对这段代码的尝试是:

from scrapy.item import Item, Field

class AgencyItem(Item):
    Phone = Field()

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from agentquery.items import AgencyItem


class AgencySpider(CrawlSpider):
   name = "agency"
   allowed_domains = ["authoradvance.com"]
   start_urls = ["http://www.authoradvance.com/agencies/"]
   rules = (Rule(SgmlLinkExtractor(allow=[r'agencies/*$']), callback='parse_item'),)

   def parse_item(self, response):
       hxs = HtmlXPathSelector(response)
       sites = hxs.select("//div[@class='section-content']")
       items = []
       for site in sites:
           item = AgencyItem()
           item['Phone'] = site.select('div[@class="phone"]/text()').extract()
           items.append(item)
       return(items)

然后我运行“scrapy crawl Agency -o items.csv -t csv” 结果爬取了0页。

怎么了?提前感谢您的帮助!

【问题讨论】:

  • 如果您想自己检查代码的哪一部分失败,您可以使用 python 调试器 pdb (docs.python.org/2/library/pdb.html) 之类的东西,它允许您在任意点停止代码的执行.通过这种方式,您可以轻松找出问题是否是正则表达式,并相应地完善您的问题,从而更容易回答!

标签: python screen-scraping scrapy web-crawler


【解决方案1】:

页面上只有一个链接满足您的正则表达式(agencies/*$):

stav@maia:~$ scrapy shell http://www.authoradvance.com/agencies/
2013-04-24 13:14:13-0500 [scrapy] INFO: Scrapy 0.17.0 started (bot: scrapybot)

>>> SgmlLinkExtractor(allow=[r'agencies/*$']).extract_links(response)
[Link(url='http://www.authoradvance.com/agencies', text=u'Agencies', fragment='', nofollow=False)]

这只是一个指向自身的链接,它没有带有section-content 类的 div:

>>> fetch('http://www.authoradvance.com/agencies')
2013-04-24 13:15:22-0500 [default] DEBUG: Crawled (200) <GET http://www.authoradvance.com/agencies> (referer: None)

>>> hxs.select("//div[@class='section-content']")
[]

因此您的循环不会迭代,items 永远不会被附加。

所以把你的正则表达式改成/agencies/.+

>>> len(SgmlLinkExtractor(allow=[r'/agencies/.+']).extract_links(response))
20

>>> fetch('http://www.authoradvance.com/agencies/agency-group')
2013-04-24 13:25:02-0500 [default] DEBUG: Crawled (200) <GET http://www.authoradvance.com/agencies/agency-group> (referer: None)

>>> hxs.select("//div[@class='section-content']")
[<HtmlXPathSelector xpath="//div[@class='section-content']" data=u'<div
class="section-content">\n\t      <di'>, <HtmlXPathSelector xpath="//div
[@class='section-content']" data=u'<div class="section-content"><div class='>]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2015-01-09
    • 1970-01-01
    相关资源
    最近更新 更多