一、已知评论页数,自动翻页爬取
import requests
from bs4 import BeautifulSoup
page = int(input('请输入评论总页数:'))+1 #整型
for i in range(1,page):
url = 'https://wordpress-edu-3autumn.localprod.oc.forchange.cn/all-about-the-future_04/comment-page-'+str(i)+'/#comments'
print('第%d页评论:'%(i))
res = requests.get(url)
soup = BeautifulSoup(res.text,'html.parser')
comments = soup.find_all('div',class_='comment-content')
for comment in comments:
print(comment.text)
二、爬豆瓣Top的相关信息
把豆瓣TOP250里面的 序号/电影名/评分/推荐语/链接 都爬取下来,然后打印出来。
代码如下:
import requests
from bs4 import BeautifulSoup
for x in range(25):
url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
res = requests.get(url,headers=headers) #注意headers=headers
#print(res.status_code) #检查requests请求返回状态码
soup = BeautifulSoup(res.text, 'html.parser')
bs = soup.find('ol', class_="grid_view")
items = bs.find_all('div',class_='item')
for item in items:
num = item.find('em',class_="").text
#查找序号
title = item.find('span', class_="title").text
#查找电影名
tes = item.find('span',class_="inq").text
#查找推荐语
comment = item.find('span',class_="rating_num").text
#查找评分
url_movie = item.find('a')['href']
print(num + '.' + title + '——' + comment + '\n' + '推荐语:' + tes +'\n' + url_movie+'\n')