如何使用bs4中的以下分页来抓取网站?

时间:2018-06-11 11:41:19

标签: python web-scraping pagination beautifulsoup

我有一个用于抓取特定网站的脚本,其中页面的编号用curveConcent(dat2013final$rank.oldage/n, dat2013final$cs.oldage, w = NULL, xlab = "Population in %", ylab = "Social Transfer Oldage in %", add = FALSE, grid = 0) 定义。 This site

这是我的剧本:

?start={}

在页面底部位于div.pagination与a.next。 Here's a screenshot.

使用from bs4 import BeautifulSoup from urllib.request import urlopen def parse(): for i in range(0, 480, 5): html = urlopen('http://rl.odessa.ua/index.php/ru/poslednie-novosti?start={}'.format(i)) soup = BeautifulSoup(html, 'lxml') for article in soup.findAll('article', class_ = 'item'): try: print('\t' + article.find('h1').find('a').get_text()) print(article.find('p').get_text() + '\n' + '*'*80) except AttributeError as e: print(e) parse() 而不是分页是不好的做法?无论如何,请帮我用分页重写上面的代码。

1 个答案:

答案 0 :(得分:1)

无论哪种方法都适合你,但找到下一个按钮会让事情变得更容易。它可以按如下方式完成:

from bs4 import BeautifulSoup
from urllib.request import urlopen

def parse():
    base_url = 'http://rl.odessa.ua/index.php'
    url = 'http://rl.odessa.ua/index.php/ru/poslednie-novosti?start=0'

    while True:
        html = urlopen(url)
        soup = BeautifulSoup(html, 'lxml')

        for article in soup.findAll('article', class_ = 'item'):
            try:    
                print('\t' + article.find('h1').find('a').get_text())
                print(article.find('p').get_text() + '\n' + '*'*80)
            except AttributeError as e:
                print(e)

        next_button = soup.find('a', class_='next', href=True)

        if next_button:
            url = base_url + next_button['href']
        else:
            break

parse()