首页 文章

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

提问于
浏览
1

我成功地 grab 了网站的第一页,但是当我试图抓取mutiples页面时,它起了作用,但结果却完全错了 .

码:

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']))

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

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 .

1 回答

  • 2

    正如Jon Clements指出的那样,格式化URL如下:

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

    您可以在pyformat.info找到有关python格式字符串的更多信息 .

相关问题