我想从http://community.sellfree.co.kr/中提取数据 . Scrapy正在运行,但它似乎只是刮掉了 start_urls
,并且没有抓取任何链接 .
我希望蜘蛛爬行整个网站 .
以下是我的代码:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from metacritic.items import MetacriticItem
class MetacriticSpider(BaseSpider):
name = "metacritic" # Name of the spider, to be used when crawling
allowed_domains = ["sellfree.co.kr"] # Where the spider is allowed to go
start_urls = [
"http://community.sellfree.co.kr/"
]
rules = (Rule (SgmlLinkExtractor(allow=('.*',))
,callback="parse", follow= True),
)
def parse(self, response):
hxs = HtmlXPathSelector(response) # The XPath selector
sites = hxs.select('/html/body')
items = []
for site in sites:
item = MetacriticItem()
item['title'] = site.select('//a[@title]').extract()
items.append(item)
return items
页面上有两种链接 . 一个是 onclick="location='../bbs/board.php?bo_table=maket_5_3'
,另一个是 <a href="../bbs/board.php?bo_table=maket_5_1&sca=프로그램/솔루션"><span class="list2">solution</span></a>
如何让爬虫跟随这两种链接?
1 回答
在开始之前,我强烈建议使用Scrapy的更新版本 . 您似乎仍在使用旧的,因为您使用的许多方法/类已被移动或弃用 .
对于手头的问题:
scrapy.spiders.BaseSpider
类不会对您指定的rules
做任何事情 . 相反,使用scrapy.contrib.spiders.CrawlSpider
类,它具有处理内置规则的功能 .接下来,您需要将
parse()
方法切换为新名称,因为CrawlSpider
在内部使用parse()
工作 . (对于本答复的其余部分,我们假设parse_page()
)要获取所有基本链接并对其进行爬网,您的链接提取器将需要更改 . 默认情况下,不应对要遵循的域使用正则表达式语法 . 以下内容将提取,您的
DUPEFILTER
将过滤掉网站上没有的链接:至于
onclick=...
链接,这些是JavaScript链接,您尝试处理的页面依赖于它们 . Scrapy无法抓取onclick=location.href="javascript:showLayer_tap('2')"
或onclick="win_open('./bbs/profile.php?mb_id=wlsdydahs'
之类的内容,因为它无法在Javascript中执行showLayer_tap()
或win_open()
.(以下是未经测试的,但应该有效,并提供您需要做的基本想法)
但是,您可以编写自己的函数来解析这些函数 . 例如,以下内容可以处理
onclick=location.href="./photo/"
:然后添加以下规则(这只处理表,根据需要展开它):