不同数量的url返回

2024-10-04 05:31:00 发布

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

我已经构建了一个爬虫程序,在一个固定的域中craws并提取匹配一个固定正则表达式的url。如果看到某个特定的url,爬虫将跟踪该链接。爬虫可以完美地提取网址,但每次我运行爬虫,它返回我不同数量的链接,即数量的链接不同,每次我运行它。我在用软泥爬。这是不是和scrapy有关?代码是:

class MySpider(CrawlSpider):
   name = "xyz"
   allowed_domains = ["xyz.nl"]
   start_urls = ["http://www.xyz.nl/Vacancies"] 
   rules = (Rule(SgmlLinkExtractor(allow=[r'\/V-\d{7}\/[\w\S]+']), callback='parse_item'),Rule(SgmlLinkExtractor(allow=[r'\?page\=\d+\&sortCriteria\=1']), follow=True),)



 def parse_item(self, response):

  outputfile = open('urllist.txt','a')
  print response.url
  outputfile.write(response.url+'\n')

Tags: 程序url数量parse链接responsenlitem
1条回答
网友
1楼 · 发布于 2024-10-04 05:31:00

不要在parse_item()方法中手动编写链接并用a模式打开文件,而是使用scrapy的内置item exporters。使用链接字段定义项目:

from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field


class MyItem(Item):
    url = Field()


class MySpider(CrawlSpider):
    name = "xyz"
    allowed_domains = ["xyz.nl"]
    start_urls = ["http://www.xyz.nl/Vacancies"]
    rules = (Rule(SgmlLinkExtractor(allow=[r'\/V-\d{7}\/[\w\S]+']), callback='parse_item'),
             Rule(SgmlLinkExtractor(allow=[r'\?page\=\d+\&sortCriteria\=1']), follow=True),)

    def parse_item(self, response):
        item = MyItem()
        item['url'] = response.url
        yield item

相关问题 更多 >