首页 > 解决方案 > 用beautifulsoup抓取并迭代几个页面,其中2个参数在url中发生变化

问题描述

我正在尝试用beautifulsoup 刮几页。但是,url中有两个参数发生变化。

到目前为止,我已经尝试过这段代码,但没有运气。

from urllib.request import urlopen

base_url= "https://superstats.dk/"
     n = 8
      for i in range(1, n+1):
       if (i == 1):
       # handle first page
    response = urlopen(base_url)
    response = urlopen(base_url + "program?aar=201" % i)
    response_plus =urlopen(response + "%2F201" % i+1)
    data = response_plus.read()

这是我想在几页上迭代的输出。

 import requests 
 from bs4 import BeautifulSoup

  r = requests.get('https://superstats.dk/program?aar=2018%2F2019')
  bs=BeautifulSoup(r.content, "lxml")

  table_div=bs.find(id="content")
  rows = table_div.find_all('tr')
  for row in rows:
     cols=row.find_all('td')
     cols=[x.text.strip() for x in cols]
     print (cols)

标签: pythonbeautifulsoup

解决方案


使用format()函数改变两个参数的值。

for i in range(1,9):
  url='https://superstats.dk/program?aar=201{}%2F201{}'.format(i,i+1)
  print(url)

希望这会有所帮助。


推荐阅读