在 Python 中使用循环抓取多个页面
Scrape multiple pages with loops in Python
我成功地抓取了网站的第一页,但是当我尝试抓取多个页面时,它成功了,但结果完全错误。
代码:
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 页。
我的代码有效,但它只是重复打印出第一页的 url 14 次。我期望的结果是使用循环从不同的页面打印出所有不同的 urls。
正如 Jon Clements 指出的那样,格式 url 如下:
res = requests.get('http://www.abcde.com/Part?Page={}&s=9&type=%8172653'.format(num)).text
您可以在 pyformat.info.
找到有关 python 格式字符串的更多信息
我成功地抓取了网站的第一页,但是当我尝试抓取多个页面时,它成功了,但结果完全错误。
代码:
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 页。
我的代码有效,但它只是重复打印出第一页的 url 14 次。我期望的结果是使用循环从不同的页面打印出所有不同的 urls。
正如 Jon Clements 指出的那样,格式 url 如下:
res = requests.get('http://www.abcde.com/Part?Page={}&s=9&type=%8172653'.format(num)).text
您可以在 pyformat.info.
找到有关 python 格式字符串的更多信息