Scrapy 启动 URL
下面这个脚本来自于这个教程,它里面有两个 start_urls
。
from scrapy.spider import Spider
from scrapy.selector import Selector
from dirbot.items import Website
class DmozSpider(Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/",
]
def parse(self, response):
"""
The lines below is a spider contract. For more info see:
http://doc.scrapy.org/en/latest/topics/contracts.html
@url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/
@scrapes name
"""
sel = Selector(response)
sites = sel.xpath('//ul[@class="directory-url"]/li')
items = []
for site in sites:
item = Website()
item['name'] = site.xpath('a/text()').extract()
item['url'] = site.xpath('a/@href').extract()
item['description'] = site.xpath('text()').re('-\s[^\n]*\\r')
items.append(item)
return items
但是,为什么它只抓取这两个网页呢?我看到有 allowed_domains = ["dmoz.org"]
,可是这两个页面里也有指向其他页面的链接,这些链接也是在 dmoz.org
这个域名下的!为什么它不抓取这些页面呢?
6 个回答
2
这个类里没有一个叫做 rules
的属性。你可以去看看这个链接:http://readthedocs.org/docs/scrapy/en/latest/intro/overview.html,然后搜索一下“rules”,可以找到一个例子。
6
start_urls 是一些链接,爬虫会从这些链接开始爬取数据。如果你想要让爬虫进行递归爬取,也就是从一个链接再去爬取它里面的链接,你应该使用 crawlspider,并为此定义一些规则。想了解更多例子,可以去看看这个链接:http://doc.scrapy.org/en/latest/topics/spiders.html。
17
start_urls
这个类属性里包含了开始抓取的网址——就这些。如果你提取了其他页面的网址,想要抓取它们,就可以用 parse
回调函数来处理这些请求,并指定另一个回调函数:
class Spider(BaseSpider):
name = 'my_spider'
start_urls = [
'http://www.domain.com/'
]
allowed_domains = ['domain.com']
def parse(self, response):
'''Parse main page and extract categories links.'''
hxs = HtmlXPathSelector(response)
urls = hxs.select("//*[@id='tSubmenuContent']/a[position()>1]/@href").extract()
for url in urls:
url = urlparse.urljoin(response.url, url)
self.log('Found category url: %s' % url)
yield Request(url, callback = self.parseCategory)
def parseCategory(self, response):
'''Parse category page and extract links of the items.'''
hxs = HtmlXPathSelector(response)
links = hxs.select("//*[@id='_list']//td[@class='tListDesc']/a/@href").extract()
for link in links:
itemLink = urlparse.urljoin(response.url, link)
self.log('Found item link: %s' % itemLink, log.DEBUG)
yield Request(itemLink, callback = self.parseItem)
def parseItem(self, response):
...
如果你还想自定义开始请求的创建,可以重写 BaseSpider.start_requests() 这个方法。