使用BeautifulSoup和Requests刮取多个分页链接

时间:2015-02-19 01:10:09

标签: python for-loop web-scraping beautifulsoup screen-scraping

Python初学者。我正试图从one category on dabs.com抓取所有产品。我已经成功地抓住了给定页面上的所有产品,但是我在迭代所有分页链接时遇到了麻烦。

现在,我已尝试使用span class ='page-list'隔离所有分页按钮,但即使这样也无法正常工作。理想情况下,我想让抓取工具继续点击下一步直到它被刮掉所有页面上的所有产品。我该怎么做?

真的很感激任何输入

from bs4 import BeautifulSoup

import requests

base_url = "http://www.dabs.com"
page_array = []

def get_pages():
    html = requests.get(base_url)
    soup = BeautifulSoup(html.content, "html.parser")

    page_list = soup.findAll('span', class="page-list")
    pages = page_list[0].findAll('a')

    for page in pages:
        page_array.append(page.get('href'))

def scrape_page(page):
    html = requests.get(base_url)
    soup = BeautifulSoup(html.content, "html.parser")
    Product_table = soup.findAll("table")
    Products = Product_table[0].findAll("tr")

    if len(soup.findAll('tr')) > 0:
        Products = Products[1:]

    for row in Products:
        cells = row.find_all('td')
        data = {
            'description' : cells[0].get_text(),
            'price' : cells[1].get_text()
        }
        print data

get_pages()
[scrape_page(base_url + page) for page in page_array]

1 个答案:

答案 0 :(得分:4)

他们的下一页按钮标题为“下一步”,您可以执行以下操作:

import requests
from bs4 import BeautifulSoup as bs

url = 'www.dabs.com/category/computing/11001/'
base_url = 'http://www.dabs.com'

r = requests.get(url)

soup = bs(r.text)
elm = soup.find('a', {'title': 'Next'})

next_page_link = base_url + elm['href']

希望有所帮助。