[英]Does Scrapy crawl ALL links with Rules?
代码源: http ://mherman.org/blog/2012/11/08/recursively-scraping-web-pages-with-scrapy/#rules我是python和scrapy的新手。 我搜索了递归蜘蛛并找到了它。
我有几个问题:
后续工作如何进行? 它只是从页面获取href链接并将其添加到请求队列中吗?
scrapy会从网页的哪一部分爬网?
下面的代码是否会抓取网页上的所有链接?
可以说我想从此网站http://downloads.trendnet.com/上爬网并下载每个文件
我可能会这样做的方法是抓取此网站上的每个链接,并检查URL的内容标头,然后下载文件是否为文件。 这可行吗?
抱歉,这是一个不好的问题。
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from craigslist_sample.items import CraigslistSampleItem
class MySpider(CrawlSpider):
name = "craigs"
allowed_domains = ["sfbay.craigslist.org"]
start_urls = ["http://sfbay.craigslist.org/search/npo"]
rules = (
Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('//a[@class="button next"]',)), callback="parse_items", follow= True),
)
def parse_items(self, response):
hxs = HtmlXPathSelector(response)
titles = hxs.xpath('//span[@class="pl"]')
items = []
for titles in titles:
item = CraigslistSampleItem()
item["title"] = titles.xpath("a/text()").extract()
item["link"] = titles.xpath("a/@href").extract()
items.append(item)
return(items)
我认为RTFM确实适用于此,但给您一个简短的答案:
关于给出的例子
rules = (
Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('//a[@class="button next"]',)), callback="parse_items", follow= True),
)
您问它爬行了什么。 它只会抓取您根据规则设置的内容。 THat表示您的漫游器每次仅爬网下一页。 对于找到的每个页面,它都会:callback = parse_items。
def parse_items(self, response):
hxs = HtmlXPathSelector(response)
titles = hxs.xpath('//span[@class="pl"]')
items = []
for titles in titles:
item = CraigslistSampleItem()
item["title"] = titles.xpath("a/text()").extract()
item["link"] = titles.xpath("a/@href").extract()
items.append(item)
return(items)
在这种情况下,parse_items要做的是检查列表中的条目。 您可以通过xpath定义列表(如您在上面看到的titles = hxs.xpath('//span[@class="pl"]')
))。 对于列表中的每个条目(即for titles in titles:
,它将文本和链接复制到一个项目中。 然后,它返回项目(也就是完成了)。
爬虫通过单击下一步按钮为发现的每个页面完成Parse_items。
在设置下,您可以包含DEPTH_LIMIT=3
。 在这种情况下,您的crawlspider只会爬行3深。
关于您发布的网站:
不,您不需要爬网蜘蛛,因为没有多个页面。 普通的基本蜘蛛就足够了。 但是,爬虫蜘蛛可以工作,我将在下面显示一些内容。 将规则设置为strict_xpath('// a',),它将遵循页面上的所有链接。
确保您的item.py包含所有必需的项目。 例如,下面它指的是item [“ link”]。 在您的item.py中,确保包含一个称为链接(区分大小写)的项目,即确保该行-link = Field()-在此处。
在parse_items下,执行以下操作:
def parse_items(self, response):
list = response.xpath('//a"')
items = []
for titles in list:
item = [INSERT WHATEVER YOU CALLED YOUR ITEM]
item["title"] = titles.xpath("/text()").extract()
item["link"] = titles.xpath("/@href").extract()
if ".pdf" in item["link"]:
SEE COMMENT BELOW
return(items)
您需要做的最后一点是检查项目管道的工作方式。 它在您的项目中使用file_urls等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.