使用从页面中抓取的字符串生成start_urls列表,以便使用scrapy进一步抓取

时间:2013-10-15 14:57:02

标签: python scrapy

请帮忙,

我从房地产网站的搜索结果页面收集了大量字符串,这些字符串与porperty id相对应。该站点使用属性ID来命名包含有关我要收集的各个属性的信息的页面。

如何将我的第一张蜘蛛创建的网址列表输入另一只蜘蛛的start_urls?

谢谢 - 我是新人。

2 个答案:

答案 0 :(得分:1)

没有必要有两只蜘蛛。蜘蛛可以使用自定义回调yield scrapy.http.Request个对象,以允许根据从初始页面集解析的值来抓取其他页面。

让我们看一个例子:

from scrapy.spider import BaseSpider
from scrapy.http import Request    

class SearchSpider(BaseSpider):
   ...
   start_urls = ['example.com/list_of_links.html']
   ...

   # Assume this is your "first" spider's parse method
   # It parses your initial search results page and generates a
   # list of URLs somehow.
   def parse(self, response):
     hxs = HtmlXPathSelector(response)
     # For example purposes we just take every link
     for href in hxs.select('//a/@href]).extract():
       yield Request(href[0], callback=self.parse_search_url)

   def parse_search_url(self, response):
      # Here is where you would put what you were thinking of as your
      # "second" spider's parse method. It operates on the results of the
      # URLs scraped in the first parse method.
      pass

正如您在此示例中所看到的,SearchSpider.parse方法解析“搜索结果页面”(或其他任何内容),并为其找到的每个URL生成一个请求。因此,不要将这些URL写入文件并尝试将它们用作第二个蜘蛛的start_urls,而只需将回调设置为同一个蜘蛛中的另一个方法(此处为:parse_search_url)。

希望这有帮助。

答案 1 :(得分:1)

作为一名老将,我明白在Scrapy中了解yield方法可能很困难。如果你没有设法获得上面的方法@audiodude详细信息(这是由于多种原因更好的方法),我使用的“解决方法”是通过使用以下方法生成我的URL(在LibreOffice或Excel中) Concatenate函数为每一行添加正确的标点符号。然后简单地将它们复制并粘贴到我的蜘蛛中,例如

start_urls = [
  "http://example.com/link1",
  "http://example.com/link2",
  "http://example.com/link3",
  "http://example.com/link4",
  "http://example.com/link5",
  "http://example.com/link6",
  "http://example.com/link7",
  "http://example.com/link8",
  "http://example.com/link9"
  ]

请注意,每行后都需要逗号(最后一行除外),并且每个链接必须用直引号括起来。使用Concatenate时使用引号会很痛苦,因此要在与您的网址相邻的单元格中生成所需结果,请键入=Concatenate(CHAR(34),A2,CHAR(34),","),假设您的网址位于单元格A2中。< / p> 祝你好运。