[英]Python - Scrapy - Creating a crawler that gets a list of URLs and crawls them
我正在尝试使用“ Scrapy”包创建一个蜘蛛,该蜘蛛获取URL列表并对其进行爬网。 我已经在stackoverflow上搜索了答案,但是找不到能够解决问题的方法。
我的脚本如下:
class Try(scrapy.Spider):
name = "Try"
def __init__(self, *args, **kwargs):
super(Try, self).__init__(*args, **kwargs)
self.start_urls = kwargs.get( "urls" )
print( self.start_urls )
def start_requests(self):
print( self.start_urls )
for url in self.start_urls:
yield Request( url , self.parse )
def parse(self, response):
d = response.xpath( "//body" ).extract()
当我爬行蜘蛛时:
Spider = Try(urls = [r"https://www.example.com"])
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(Spider)
process.start()
我在打印self.start_urls时得到以下信息:
为什么我什么都没有? 有没有其他方法可以解决此问题? 或我的蜘蛛班上有什么错误吗?
感谢您提供的任何帮助!
我建议在process.crawl
使用Spider类,并在其中传递urls
参数。
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy import Request
class Try(scrapy.Spider):
name = 'Try'
def __init__(self, *args, **kwargs):
super(Try, self).__init__(*args, **kwargs)
self.start_urls = kwargs.get("urls")
def start_requests(self):
for url in self.start_urls:
yield Request( url , self.parse )
def parse(self, response):
d = response.xpath("//body").extract()
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(Try, urls=[r'https://www.example.com'])
process.start()
如果我跑步
process.crawl(Try, urls=[r"https://www.example.com"])
然后它将urls
发送给Try
正如我期望的那样。 甚至我也不需要start_requests
。
import scrapy
class Try(scrapy.Spider):
name = "Try"
def __init__(self, *args, **kwargs):
super(Try, self).__init__(*args, **kwargs)
self.start_urls = kwargs.get("urls")
def parse(self, response):
print('>>> url:', response.url)
d = response.xpath( "//body" ).extract()
from scrapy.crawler import CrawlerProcess
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(Try, urls=[r"https://www.example.com"])
process.start()
但是如果我用
spider = Try(urls = ["https://www.example.com"])
process.crawl(spider)
那么看起来它会运行没有urls
新Try
,然后列表为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.