【问题标题】:How to scrape a website using following pagination in bs4?如何在 bs4 中使用以下分页来抓取网站?
【发布时间】:2018-11-20 15:42:42
【问题描述】:

我有一个抓取特定网站的脚本,其中页面的编号是用?start={} 定义的。 This site

这是我的脚本:

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() 

页面底部是div.pagination 和a.next。 Here's a screenshot.

使用range() 代替分页是一种不好的做法吗?无论如何,请帮助我使用分页重写上面的代码。

【问题讨论】:

    标签: python web-scraping pagination beautifulsoup


    【解决方案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() 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多