我有一个运行良好的抓取工具。但是,我只希望它遵循包含特定关键字或短语的链接。我以为知道了,但是我的输出不正确。
from scrapy.selector import HtmlXPathSelector
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.utils.url import urljoin_rfc
from webcrawler.items import SitegraphItem
class GraphspiderSpider(CrawlSpider):
name = "examplespider"
custom_settings = {
'DEPTH_LIMIT': '2',
}
allowed_domains = []
start_urls = (
'http://www.example.com/products/',
)
rules = (
Rule(LinkExtractor(allow=r'/'), callback='parse_item', follow=True),
)
def parse_item(self, response):
hxs = HtmlXPathSelector(response)
i = SitegraphItem()
i['url'] = response.url
# i['http_status'] = response.status
llinks=[]
for anchor in hxs.select('//a[text()="keyword"]/@href'):
href=anchor.select('@href').extract()[0]
if not href.lower().startswith("javascript"):
llinks.append(urljoin_rfc(response.url,href))
i['linkedurls'] = llinks
return i
def _response_downloaded(self, response):
filename = response.url.split("/")[-1] + '.html'
with open(filename, 'wb') as f:
f.write(response.body)
rule = self._rules[response.meta['rule']]
return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow)
我在hxs.select段中添加了“关键字”语句,但这显然是不正确的。我不确定如何正确使用关键字。
答案 0 :(得分:0)
查看是否可以使用LinkExtractor属性来实现链接过滤逻辑。
否则,请使用Spider
而不是CrawlSpider
。 CrawlSpider
仅在其支持的有限用例中有用; Spider
适用于所有用例。