首页 > 解决方案 > Scrapy linkextractor ignores parameters behind the sign # and thus will not follow the link

问题描述

I am trying to crawl a website with scrapy where the pagination is behind the sign "#". This somehow makes scrapy ignore everything behind that character and it will always only see the first page.

e.g.:

http://www.rolex.de/de/watches/find-rolex.html#g=1&p=2

If you enter a question mark manually, the site will load page 1

http://www.rolex.de/de/watches/find-rolex.html?p=2

The stats from scrapy tell me it fetched the first page:

DEBUG: Crawled (200) http://www.rolex.de/de/watches/datejust/m126334-0014.html> (referer: http://www.rolex.de/de/watches/find-rolex.html)

My crawler looks like this:

start_urls = [
    'http://www.rolex.de/de/watches/find-rolex.html#g=1',
    'http://www.rolex.de/de/watches/find-rolex.html#g=0&p=2',
    'http://www.rolex.de/de/watches/find-rolex.html#g=0&p=3',
]

rules = (
    Rule(
        LinkExtractor(allow=['.*/de/watches/.*/m\d{3,}.*.\.html']), 
        callback='parse_item'
    ),       
    Rule(
        LinkExtractor(allow=['.*/de/watches/find-rolex(/.*)?\.html#g=1(&p=\d*)?$']), 
        follow=True
    ),
)

How can I make scrapy ignore the # inside the url and visit the given URL?

标签: scrapy

解决方案


Scrapy 执行 HTTP 请求。URL 中“#”之后的数据不是 HTTP 请求的一部分,它由 JavaScript 使用。

正如评论中所建议的,该站点使用 AJAX 加载数据。

此外,它不使用 AJAX 中的分页:该站点在单个请求中以 JSON 格式下载整个手表列表,然后使用 JavaScript 完成分页。

因此,您可以只使用 Web 浏览器的开发人员工具的 Network 选项卡来查看获取 JSON 数据的请求,并执行类似的请求,而不是请求 HTML 页面。

但是请注意,您不能LinkExtractor用于 JSON 数据。您应该简单地使用 Python 解析响应json并在那里迭代 URL。


推荐阅读