0

我是网络抓取的新手,在尝试无限滚动抓取网站时遇到了一些问题。我看了一些其他问题,但我找不到答案,所以我希望有人能在这里帮助我。

我正在网站http://www.aastocks.com/tc/stocks/analysis/stock-aafn/00001/0/all/上工作。我有以下(非常基本的)一段代码,我可以在第一页上找到每一篇文章(20 个条目)。

    def parse(self, response):

        # collect all article links
        news = response.xpath("//div[starts-with(@class,'newshead4')]//a//text()").extract()  
        # visit each news link and gather news info
        for n in news:
            url = urljoin(response.url, n)
            yield scrapy.Request(url, callback=self.parse_news)

但是,我不知道如何转到下一页。我在线阅读了一些教程,例如转到 Inspect -> Network 并在滚动后观察请求 URL,它返回http://www.aastocks.com/tc/resources/datafeed/getmorenews.ashx?cat=all&newstime=905169272&newsid=NOW.895783&period=0&key=&symbol=00001了我找不到分页或其他模式的指示以帮助我转到下一页。当我将此链接复制到新选项卡时,我会看到一个带有下一页新闻的 json 文档,但没有带有它的 url。在这种情况下,我该如何解决?非常感谢!

4

1 回答 1

-1

关联

http://www.aastocks.com/tc/resources/datafeed/getmorenews.ashx?cat=all&newstime=905169272&newsid=NOW.895783&period=0&key=&symbol=00001

提供带有值的 JSON 数据NOW.XXXXXX,您可以使用这些值生成新闻链接

"http://www.aastocks.com/tc/stocks/analysis/stock-aafn-con/00001/" + "NOW.XXXXXX" + "/all"

如果您向下滚动几次,您会看到下一页会生成类似的链接,但参数newstime不同newsid

如果您检查 JSON 数据,那么您将看到最后一项具有值'dtd'并且'id'与参数相同newstimenewsid在用于下载 JSON 数据以供下一页的链接中。

因此,您可以生成链接以获取下一页的 JSON 数据。

"http://www.aastocks.com/tc/resources/datafeed/getmorenews.ashx?cat=all&newstime=" + DTD + "&newsid=" + ID + "&period=0&key=&symbol=00001"

工作示例requests

import requests

newstime = '934735827'
newsid = 'HKEX-EPS-20190815-003587368'

url = 'http://www.aastocks.com/tc/resources/datafeed/getmorenews.ashx?cat=all&newstime={}&newsid={}&period=0&key=&symbol=00001'
url_article = "http://www.aastocks.com/tc/stocks/analysis/stock-aafn-con/00001/{}/all"

for x in range(5):

    print('---', x, '----')
    print('data:', url.format(newstime, newsid))

    # get JSON data
    r = requests.get(url.format(newstime, newsid))
    data = r.json()

    #for item in data[:3]: # test only few links
    for item in data[:-1]: # skip last link which gets next page

        # test links to articles
        r = requests.get(url_article.format(item['id']))
        print('news:', r.status_code, url_article.format(item['id']))

    # get data for next page
    newstime = data[-1]['dtd']
    newsid = data[-1]['id']
    print('next page:', newstime, newsid)
于 2019-09-15T21:54:56.307 回答