请求网址中"&page="的问题,可以通过修改该参数的值来请求不同的数据页的例子
时间: 2024-02-22 07:01:03 浏览: 17
当请求网址中包含类似"&page="这样的参数时,我们可以通过修改该参数的值来请求不同的数据页。以下是一个请求豆瓣电影Top250不同页面的例子:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
params = {'start': 0, 'filter': ''}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
for i in range(10):
response = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
movie_items = soup.find_all('div', {'class': 'hd'})
for item in movie_items:
title = item.a.span.get_text()
print(title)
params['start'] += 25
```
这个例子中,我们首先设置了请求的基本网址、查询参数和请求头。然后,我们使用一个for循环来请求不同的数据页。每次请求时,我们将start参数的值加25,以获取下一页的数据。最后,我们使用BeautifulSoup解析每个页面的内容,并提取出每部电影的名称。
需要注意的是,在实际爬虫中,我们需要更加谨慎地设置请求频率,以免给网站服务器带来过大的负担。