在 Python 中抓取网站的第二页不起作用

Scraping the second page of a website in Python does not work

假设我想抓取数据 here

我可以在 Python 2.7 中使用 urlopenBeautifulSoup 做得很好。

现在,如果我想使用 this address 从第二页抓取数据。

我得到的是第一页的数据!我使用Chrome的"view page source"查看了第二页的页面源,内容属于第一页!

如何从第二页抓取数据?

该页面具有相当异步的性质,有 XHR 请求形成搜索结果,使用 requests 在您的代码中模拟它们。示例代码作为您的起点:

from bs4 import BeautifulSoup
import requests

url = 'http://www.amazon.com/Best-Sellers-Books-Architecture/zgbs/books/173508/#2'
ajax_url = "http://www.amazon.com/Best-Sellers-Books-Architecture/zgbs/books/173508/ref=zg_bs_173508_pg_2"

def get_books(data):
    soup = BeautifulSoup(data)

    for title in soup.select("div.zg_itemImmersion div.zg_title a"):
        print title.get_text(strip=True)


with requests.Session() as session:
    session.get(url)

    session.headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        'X-Requested-With': 'XMLHttpRequest'
    }

    for page in range(1, 10):
        print "Page #%d" % page

        params = {
            "_encoding": "UTF8",
            "pg": str(page),
            "ajax": "1"
        }
        response = session.get(ajax_url, params=params)
        get_books(response.content)

        params["isAboveTheFold"] = "0"
        response = session.get(ajax_url, params=params)
        get_books(response.content)

别忘了成为 good web-scraping citizen 并遵守使用条款。