【发布时间】:2017-09-15 12:10:23
【问题描述】:
设置
我正在使用here 给出的 scrapy 示例抓取房屋广告。
在我的例子中,我使用指向住房广告页面的链接而不是作者页面,随后废弃住房广告页面以获取信息。
问题
我的代码成功地跟踪到住房广告页面的链接,并抓取每个广告的信息。但是,它只对初始页面这样做,即它不遵循分页链接。
到目前为止的代码
class RoomsSpider(scrapy.Spider):
name = 'rooms'
start_urls = ['https://www.spareroom.co.uk/flatshare/london']
def parse(self, response):
# follow links to ad pages
for href in response.xpath(
'//*[@id="maincontent"]/ul/li/article/header[1]',
).css('a::attr(href)').extract():
yield scrapy.Request(response.urljoin(href),
callback=self.parse_ad)
# follow pagination links
next_page = response.xpath(
'//*[@id="maincontent"]/div[2]/ul[2]/li/strong/a/@href',
).extract()
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)
def parse_ad(self, response):
# code extracting ad information follows here,
# finalising the code with a yield function.
所以,我基本上是按照这个例子来的。我在运行代码时没有收到关于分页链接部分的错误,并且查询路径是正确的(我相信)。
我是否在代码中正确放置了# follow pagination links 部分?我迷路了。
【问题讨论】:
-
你在scrapy shell中测试过
response.xpath('//*[@id="maincontent"]/div[2]/ul[2]/li/strong/a',).css('a::attr(href)').extract()吗?我怀疑这不起作用,因为将 XPath 的...../a选定元素与 CSSa后代链接永远不会匹配(链接没有链接子项)。如果您真的想使用 XPath 和 CSS,请尝试 XPath/*[@id="maincontent"]/div[2]/ul[2]/li/strong/a/@href或/*[@id="maincontent"]/div[2]/ul[2]/li/strong后跟 CSSa::attr(href) -
@paultrmbrth,
response.xpath('//*[@id="maincontent"]/div[2]/ul[2]/li/strong/a',).css('a::attr(href)').extract()在 Scrapy shell 中工作。也就是说,它为我提供了“下一个”href。 -
我已将其更改为
response.xpath('//[@id="maincontent"]/div[2]/ul[2]/li/strong/a/@href').extract(),它提供了href。我会在问题中更改它。 -
@paultrmbrth。我发现了问题,href 作为单元素列表返回,而不是字符串。只需将其更改为字符串,现在一切正常...感谢您与我一起思考。
-
对,我正要说你链接的例子使用
.extract_first(),而不是.extract()
标签: python pagination scrapy