爬取并解析https://movie.douban.com/review/best/
时间: 2023-08-22 14:04:56 浏览: 53
好的,以下是一个简单的爬取并解析豆瓣最受欢迎影评的示例代码:
```
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/review/best/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
reviews = soup.find_all('div', class_='review-item')
for review in reviews:
title = review.h2.a.text.strip()
content = review.find('div', class_='short-content').text.strip()
rating = review.find('span', class_='rating').text.strip()
time = review.find('span', class_='main-meta').text.strip()
print(title, content, rating, time)
```
该代码会爬取豆瓣最受欢迎影评页面,并获取影评的标题、内容、评分和评论时间等信息。需要注意的是,豆瓣网站有反爬机制,如果频繁请求网站可能会被封禁IP,建议在使用时适当控制请求频率。
相关问题
爬取https://movie.douban.com/subject/1305690/所有短评的代码
以下是使用Python和BeautifulSoup库爬取豆瓣电影《肖申克的救赎》(https://movie.douban.com/subject/1305690/)所有短评的代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/subject/1305690/comments?start=0&limit=20&sort=new_score&status=P'
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'}
comments = []
while True:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
comment_div_list = soup.find_all('div', class_='comment')
for comment_div in comment_div_list:
comment = comment_div.find('span', class_='short').text.strip()
comments.append(comment)
next_page = soup.find('a', class_='next')
if next_page:
url = 'https://movie.douban.com' + next_page['href']
else:
break
print(comments)
```
注:以上代码可能会触发豆瓣的反爬虫机制,建议使用代理或者加入适当的延时等策略来规避反爬虫机制。另外,爬虫行为需要遵守相关法律法规和网站的Robots协议。
爬取https://movie.douban.com/subject/3552028/的所有短评
这里提供一种Python爬取豆瓣电影短评的方法,需要用到requests和BeautifulSoup库。
首先,我们需要向该网页发送请求,获取网页源代码。代码如下:
```python
import requests
url = "https://movie.douban.com/subject/3552028/comments?start=0&limit=20&status=P&sort=new_score"
response = requests.get(url)
html = response.text
```
接着,我们需要使用BeautifulSoup对网页源代码进行解析,以便提取我们所需的信息。代码如下:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
comments = soup.find_all("span", class_="short")
for c in comments:
print(c.string)
```
这段代码中,我们使用find_all方法找到所有class为"short"的span标签,这些标签包含了我们需要获取的短评信息。然后,我们遍历每个标签,并使用string属性获取标签内的文本内容。
此外,我们需要注意到豆瓣电影短评采用了分页的方式,每页最多显示20条短评。如果要爬取所有短评,需要在url中指定start参数并逐页爬取。完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = "https://movie.douban.com/subject/3552028/comments?start={}&limit=20&status=P&sort=new_score"
start = 0
while True:
response = requests.get(url.format(start))
soup = BeautifulSoup(response.text, "html.parser")
comments = soup.find_all("span", class_="short")
if len(comments) == 0:
break
for c in comments:
print(c.string)
start += 20
```
这段代码中,我们使用while循环,每次递增20的start参数值,直到获取到的短评数为0为止。注意,豆瓣电影短评是需要登录才能进行查看的,因此如果你没有登录,可能无法获取到所有的短评。