首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用父目录的抓取LinkExtractor抓取链接

使用父目录的抓取LinkExtractor抓取链接
EN

Stack Overflow用户
提问于 2020-06-04 01:04:49
回答 1查看 64关注 0票数 1

使用Scrapy中的基本CrawlerSpider,我正在尝试爬取页面。我要抓取的页面中的相关链接都以父目录符号..开头,而不是以完整的域开头。

例如,如果我从页面https://www.mytarget.com/posts/4/friendly-url开始,并且我想在/posts中抓取每个帖子,那么该页面上的相关链接将是:

代码语言:javascript
复制
'../55/post-name'
'../563/another-name'

而不是:

代码语言:javascript
复制
'posts/55/post-name'
'posts/563/another-name'

或者哪种方式更好:

代码语言:javascript
复制
'https://www.mytarget.com/posts/55/post-name'
'https://www.mytarget.com/posts/563/another-name'

allowed_domains中删除mytarget.com似乎没有什么帮助。crawler在网站上找不到与..父目录链接引用匹配的新链接。

下面是我的代码:

代码语言:javascript
复制
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from exercise_data_collector.items import Post

class MyCrawlerSpider(CrawlSpider):
    name = 'my_crawler'
    allowed_domains = ['mytarget.com']
    start_urls = ['https://www.mytarget.com/posts/4/friendly-url']

    rules = (
        Rule(LinkExtractor(allow=r'posts/[0-9]+/[0-9A-Za-z-_]+'), callback='parse_item', follow=True),
        Rule(LinkExtractor(allow=r'/posts\/[0-9]+\/[0-9A-Za-z-_]+'), callback='parse_item', follow=True),
        Rule(LinkExtractor(allow=r'/..\/[0-9]+\/[0-9A-Za-z-_]+'), callback='parse_item', follow=True),
    )

    def parse(self, response):
        links = self.le1.extract_links(response)

        item = Post()
        item["page_title"] = response.xpath('//title/text()').get()
        item["name"] = response.xpath("//div[@class='container']/div[@class='row']/div[1]/div[1]/text()[2]").get().replace('->','').strip()
        item['difficulty'] = response.xpath("//p[strong[contains(text(), 'Difficulty')]]/text()").get().strip()

        return item

我不确定如何配置正则表达式来获取相关链接,甚至测试正则表达式是否在regexr.com之外工作。

我怎么能像这样抓取页面呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-15 21:51:14

我用这个正则表达式r'posts/[0-9]+/[A-Za-z-_]+'解决了这个问题

代码语言:javascript
复制
class MyCrawlerSpider(CrawlSpider):
    name = 'my_crawler'
    allowed_domains = ['mytarget.com']
    start_urls = ['https://www.mytarget.com/posts/4/friendly-url']

    rules = (
        Rule(LinkExtractor(allow=r'exercises/[0-9]+/[A-Za-z-_]+'), callback='parse_item', follow=True)
    )
    def parse(self, response):
        links = self.le1.extract_links(response)

        item = Post()
        item["page_title"] = response.xpath('//title/text()').get()
        item["name"] = response.xpath("//div[@class='container']/div[@class='row']/div[1]/div[1]/text()[2]").get().replace('->','').strip()
        item['difficulty'] = response.xpath("//p[strong[contains(text(), 'Difficulty')]]/text()").get().strip()

        return item

我确实遇到了一个递归问题,posts/12/page.html更改为posts/12/12/page.html ... posts/12/12/12/12/12/12/page.html。我认为这可能是他们网站上的一个错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62178548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档