python - 用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)
解决方案
使用format()
函数改变两个参数的值。
for i in range(1,9):
url='https://superstats.dk/program?aar=201{}%2F201{}'.format(i,i+1)
print(url)
希望这会有所帮助。
推荐阅读
- javascript - 如何以角度触发主机组件上的动画?
- git - 我可以创建一个从开源存储库克隆的存储库,并且仍然能够将他们的新更新合并到我的存储库中吗?
- java - 以编程方式创建的下划线微调器
- css - 静态 CSS 文件不适用于路由器 Express
- android - Android:从在活动上扩展的 AbstractActivity 类调用变量时出现问题
- sql - 如何比较两个表?
- node.js - 用户客户端可以使用浏览器控制台更改身份验证状态吗?
- docker - Kubernetes 1.18 警告 ImageGCFailed 错误无法获取 imageFs 信息:无法在内存缓存中找到数据
- security - 使用 oauth2 客户端凭据防止中间人攻击
- apache-beam - ParDo 操作应该有多小才能获得良好的性能和光束作业的缩放?