用python爬取豆瓣电影的代码
时间: 2023-10-03 19:10:51 浏览: 59
以下是用Python爬取豆瓣电影的代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
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'}
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
movie_list = soup.find('ol', class_='grid_view').find_all('li')
for movie in movie_list:
title = movie.find('span', class_='title').text
rating = movie.find('span', class_='rating_num').text
print(title, rating)
```
这个代码会爬取豆瓣电影排行榜前250部电影的电影名和评分,并将它们打印到控制台上。需要注意的是,为了避免被豆瓣网站反爬虫机制封禁IP,我们设置了headers模拟浏览器访问。
相关问题
用python爬取豆瓣电影
好的,以下是利用 Python 爬取豆瓣电影的基本步骤:
1. 安装相关库
我们需要使用 requests 库来发送 HTTP 请求,以及使用 BeautifulSoup 库来解析 HTML 页面。你可以使用以下命令安装这两个库:
```python
pip install requests beautifulsoup4
```
2. 发送 HTTP 请求
我们可以使用 requests 库中的 get 方法来向豆瓣电影的网站发送 HTTP 请求,并获得响应:
```python
import requests
url = 'https://movie.douban.com/top250'
response = requests.get(url)
```
3. 解析 HTML 页面
我们可以使用 BeautifulSoup 库将响应的 HTML 页面解析成 BeautifulSoup 对象:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
```
4. 提取电影数据
在 BeautifulSoup 对象中,我们可以使用 find 或 find_all 方法来查找特定的 HTML 标签和属性。通过查看豆瓣电影 Top250 页面的 HTML 结构,我们可以发现每个电影都包含在一个 class 为 "item" 的 div 标签中,而每个电影的名称和评分则分别包含在 class 为 "title" 和 "rating_num" 的 span 标签中。因此,我们可以使用以下代码来提取电影名称和评分:
```python
movies = soup.find_all('div', class_='item')
for movie in movies:
title = movie.find('span', class_='title').text.strip()
rating = movie.find('span', class_='rating_num').text.strip()
print(title, rating)
```
以上就是利用 Python 爬取豆瓣电影的基本步骤。当然,还可以根据需要提取更多的电影数据,例如导演、演员、上映时间等。
python爬取豆瓣电影top250代码
以下是使用Python爬取豆瓣电影Top250的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
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'}
movie_list = []
for i in range(0, 250, 25):
res = requests.get(url, headers=headers, params={'start': str(i)})
soup = BeautifulSoup(res.text, 'html.parser')
movies = soup.find_all('div', {'class': 'info'})
for movie in movies:
title = movie.find('span', {'class': 'title'}).text
rating = movie.find('span', {'class': 'rating_num'}).text
quote = movie.find('span', {'class': 'inq'}).text if movie.find('span', {'class': 'inq'}) else None
movie_list.append({'title': title, 'rating': rating, 'quote': quote})
for movie in movie_list:
print(movie['title'], movie['rating'], movie['quote'])
```
这段代码使用了requests库和BeautifulSoup库来获取网页内容和提取页面信息。循环遍历每一页,找到每部电影的标题、评分和简介(如果有的话),并将它们保存在一个列表中。最后,打印出每部电影的信息。