【问题标题】:Iterating through a site's pages with python and Beautiful Soup使用 python 和 Beautiful Soup 遍历站点的页面
【发布时间】:2016-05-09 20:09:08
【问题描述】:

有没有办法遍历格式为的页面档案

'http://base_url/page=#' - 其中 # 是第 2 个页码?

理想情况下,我想在“base_url”之后的每个连续页面上部署我的爬虫

是python中的一个函数或for循环,其中base_url将被迭代:

page = i in range(nth)
base_url ='http://base_url/page={}'

例如http://www.businessinsider.com/?page=3http://www.businessinsider.com/

【问题讨论】:

    标签: python loops web-scraping iteration


    【解决方案1】:

    您可以像这样请求每个页面:

    # python 2
    from urllib2 import urlopen
    # python 3
    from urllib.request import urlopen
    
    base_url = "http://example.com/"
    
    # request page 1 through 10
    n = 10
    for i in range(1, n+1):
        if (i == 1):
            # handle first page
            response = urlopen(base_url)
        response = urlopen(base_url + "?page=%d" % i)
    
        data = response.read()
        # handle data here
    

    编辑:urlopen() 返回一个 HTTPResponseaddinfourl 对象(取决于您的 Python 版本) - 您需要调用 .read() 以获取数据字符串。 (我也更新了上面的示例代码)。

    【讨论】:

    • 当我用业务运行它时...url 我得到 x 10 - >
    • 这很奇怪 - 在我的测试中,它返回一个 HTTPResponse(您可以将其视为文件对象)。你能把你的代码贴在pastebin上吗? (例如bpaste.net
    • 哦-addinfourl是python 2返回的对象(我用的是python 3,所以没意识到)。如果您在 addinfourl 对象上调用 .read(),您将获得字符串形式的数据。
    • 如果我没记错的话,response.url 是 url,所以你可以在 for 循环中执行 if response.url == base_url: continue
    • 另外,如果您不想要首页,只需将range(1, n+1) 更改为range(2, n+1) 并删除if (i == 1) 语句。
    猜你喜欢
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2016-11-19
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多