【问题标题】:Scraping the second page of a website in Python does not work在 Python 中抓取网站的第二页不起作用
【发布时间】:2015-07-25 14:18:39
【问题描述】:

假设我想抓取数据here

我可以在 Python 2.7 中使用 urlopenBeautifulSoup 很好地做到这一点。

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

我得到的是第一页的数据!我用Chrome的“查看页面源”查看了第二页的页面源,内容属于第一页!

如何从第二页抓取数据?

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup urlopen


    【解决方案1】:

    该页面具有相当异步的性质,有 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 并遵守使用条款。

    【讨论】:

    • 哇,答案很好,效果很好。两个问题: 1. 您是如何得知 XHR 请求的? 2、为什么urlajax_url中的第二页地址.../#2而不是第一页?
    • 还有一个问题:在 abobe 函数中:get_books 如果我在 for 循环中添加一行,那么除了将书名打印到屏幕上之外,它还会将其写入文件中,然后事情就变得搞砸了,并非所有标题都打印在屏幕上,也没有打印到文件中。此代码中是否存在时间敏感项?
    • @TJ1 1. 我使用过浏览器开发工具(网络选项卡) 2. 这可能是一个错字,尽管ajax_url 很重要——数据是通过 ajax 加载的
    • @TJ1 3. 我现在不知道。如果您有困难,最好单独提出一个问题,以便更多人可以提供帮助。谢谢。
    • Alecxe:你能自己试试这个吗?看看如果你把数据写入文件会发生什么?
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多