代码之家  ›  专栏  ›  技术社区  ›  Makiyo

在Python中使用循环刮取多个页面

  •  2
  • Makiyo  · 技术社区  · 8 年前

    我成功地抓取了网站的第一个页面,但当我试图抓取多个页面时,它起了作用,但结果是完全错误的。

    代码:

    import requests
    from bs4 import BeautifulSoup
    from urllib.parse import urljoin
    for num in range(1,15):
        res = requests.get('http://www.abcde.com/Part?Page={num}&s=9&type=%8172653').text
        soup = BeautifulSoup(res,"lxml")
        for item in soup.select(".article-title"):
            print(urljoin('http://www.abcde.com',item['href']))
    

    它只更改了每个页面url中的一个数字,例如,

    http://www.abcde.com/Part?Page=1&s=9&type=%8172653
    http://www.abcde.com/Part?Page=2&s=9&type=%8172653
    

    我一共有14页。

    我的代码成功了,但它只是重复打印出了14次第一页的url。我期望的结果是使用循环从不同的页面打印出所有不同的URL。

    1 回复  |  直到 8 年前
        1
  •  3
  •   allo    8 年前

    正如Jon Clements所指出的,url格式如下:

    res = requests.get('http://www.abcde.com/Part?Page={}&s=9&type=%8172653'.format(num)).text
    

    有关python格式字符串的更多信息,请访问 pyformat.info .