【问题标题】:Scrapy isnt scraping the next pageScrapy 不会抓取下一页
【发布时间】:2019-11-10 00:06:56
【问题描述】:

我正在尝试从 skynewsarabia.com 上抓取文章新闻

class SkyNewsSportsSpider(scrapy.Spider):

    name = 'sky_news_sports'

sport = "https://www.skynewsarabia.com/sport/"
custom_settings = {
    'FEED_EXPORT_FIELDS': ["article_content", "tags"],
}
allowed_domains = ['www.skynewsarabia.com']

first_token = "1569266773000"
scrape_this_link = "https://api.skynewsarabia.com//rest/v2/latest.json?defaultSectionId=6&nextPageToken={}&pageSize=20&types=ARTICLE"
start_urls = [scrape_this_link.format(first_token)]
urls = []

def parse(self, response):
    articles = json.loads(response.text)

    # to get the link for each article we need to combine both the id and the urlFriendlySuffix in one link
    for article in range(0, len(articles["contentItems"])):
        article_id = articles["contentItems"][article]["id"]
        article_url = articles["contentItems"][article]["urlFriendlySuffix"]
        relative_link = article_id + "-" + article_url
        full_link = self.sport + relative_link
        self.urls.append(full_link)

    for url in self.urls:
        yield scrapy.Request(url=url, callback=self.parse_details)

    self.urls = []

    print("Before Check")
    self.first_token = articles["nextPageToken"]
    if self.first_token is not None:
        next_page = self.scrape_this_link.format(self.first_token)
        print("I am inside!")
        print(next_page)
        yield response.follow(url=next_page, callback=self.parse)

def parse_details(self, response):
    pass

这里的基本思想是你首先抓取一个有 20 个链接的链接。除此之外,第一个链接还有下一个链接的标记,您需要将其添加到下一个 URL,以便您可以抓取接下来的 20 个链接。但是,我面临的问题是,当您第一次运行脚本时,它正在获取下一个令牌并获取该令牌的所有链接,然后它就停止了!所以我只是刮了20个链接!当我打印 first_token 时,它给了我与脚本中默认提供的 1569266773000 不同的东西。

【问题讨论】:

    标签: web-scraping scrapy


    【解决方案1】:

    您需要将allowed_domains = ['www.skynewsarabia.com'] 更改为allowed_domains = ['skynewsarabia.com']。或者完全删除 allowed_domains 变量。

    由于您已指定主机名www,因此 Scrapy 会将对api.skynewsarabia.com 的请求过滤为异地,并且呼叫刚刚被挂断。

    附加提示:尝试在代码中使用self.logger.infoself.logger.debug 而不是print 命令。

    【讨论】:

    • 是的,就是这样,它正在工作,只需要删除allowed_domains。谢谢你的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 2014-03-20
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多