使用从页面抓取的字符串来生成用于进一步使用scrapy抓取的起始网址列表

2024-10-01 15:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮忙

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

如何将第一个spider创建的url列表添加到另一个spider的start_url中?在

谢谢-我是新来的。在


Tags: 字符串信息idurl列表属性站点网站
2条回答

作为一个noob伙伴,我理解你很难理解Scrapy中的yield方法。如果您无法获得上面的@audiodude details方法(由于许多原因,这是一种更好的方法),我使用的一种“解决方法”是通过使用Concatenate函数为每一行添加正确的标点符号来生成我的url(在LibreOffice或Excel中)。然后简单地复制并粘贴到我的蜘蛛上

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时,使用引号是一件很麻烦的事情,所以为了产生所需的结果,在url附近的单元格中,输入=Concatenate(CHAR(34),A2,CHAR(34),","),假设url在A2单元格中。在

祝你好运。在

没有必要养两只蜘蛛。spider可以使用自定义回调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方法解析“searchresults page”(或其他内容),并为它找到的每个URL生成一个请求。因此,与其将这些url写入一个文件并尝试将它们用作第二个spider的起始url,只需将回调设置为同一个spider中的另一个方法(这里:parse_search_url)来生成它们。在

希望这有帮助。在

相关问题 更多 >

    热门问题