python爬取豆瓣喜剧电影
时间: 2023-11-17 16:06:34 浏览: 52
为了爬取豆瓣喜剧电影,我们可以使用Python的requests和BeautifulSoup库。具体步骤如下:
1. 首先,我们需要使用requests库向豆瓣电影网站发送请求,并获取响应内容。代码如下:
```python
import requests
url = 'https://movie.douban.com/tag/#/?sort=S&range=9,10&tags=%E5%96%9C%E5%89%A7'
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'}
response = requests.get(url, headers=headers)
```
2. 接下来,我们需要使用BeautifulSoup库解析响应内容,并提取出我们需要的电影信息。代码如下:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
movie_list = soup.find(class_='list-wp').find_all('a', class_='item')
for movie in movie_list:
print(movie.find(class_='title').string)
```
在这个例子中,我们使用了find()方法和find_all()方法来查找HTML标签,并使用string属性来获取标签的文本内容。
3. 最后,我们可以将电影信息保存到文件中,以便后续处理。代码如下:
```python
with open('movies.txt', 'w', encoding='utf-8') as f:
for movie in movie_list:
f.write(movie.find(class_='title').string + '\n')
```
这里我们使用了with语句来打开文件,并使用write()方法将电影名称写入文件中。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)