【发布时间】: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