使用Scrapy递归抓取网页
“http://www.example.com/listing.php?num=2&”
这是我写的爬虫代码,它可以在一个页面上显示链接列表:
from scrapy.log import *
from crawler_bhinneka.settings import *
from crawler_bhinneka.items import *
import pprint
from MySQLdb import escape_string
import urlparse
def complete_url(string):
"""Return complete url"""
return "http://www.example.com" + string
class BhinnekaSpider(CrawlSpider):
name = 'bhinneka_spider'
start_urls = [
'http://www.example.com/listing.php?'
]
def parse(self, response):
hxs = HtmlXPathSelector(response)
# HXS to find url that goes to detail page
items = hxs.select('//td[@class="lcbrand"]/a/@href')
for item in items:
link = item.extract()
print("my Url Link : ",complete_url(link))
我知道我可以在第一页获取所有链接。
我想让这个爬虫使用递归规则,去跟踪下一页的链接。你知道怎么在爬虫中尝试我的规则,以获取下一页的链接值吗?
编辑
@Toan,谢谢你的回复。 我试着按照你发给我的教程做,但我只获取到了第一页(第一页面)的项目值。
我查看了这个网址的源代码: “http://sfbay.craigslist.org/npo/”,但我没有看到在这个restrict_xpaths中匹配的xpath值(class = "nextpage"在源代码中并不存在)。
这是你的链接示例规则:
rules = (Rule (SgmlLinkExtractor (allow = ("index \ d00 \. html") restrict_xpaths = ('/ / p [@ class = "nextpage"]'))
, Callback = "parse_items" follow = True)
)
1 个回答
0
Scrapy的链接提取器是用来从网页中提取链接的工具。
这里有一个例子: http://mherman.org/blog/2012/11/08/recursively-scraping-web-pages-with-scrapy/#.U9Dl8h_FsUQ