python爬取豆瓣海报
时间: 2023-11-04 07:05:19 浏览: 156
要使用Python爬取豆瓣电影海报,你可以通过以下步骤实现:
1. 使用urllib库中的request模块发送请求并获取豆瓣电影网页的源代码。
2. 使用BeautifulSoup库解析源代码,以便查找需要的信息。可以使用find方法找到class为"list-wp"的div标签,它包含了电影海报的信息。
3. 提取所需的数据,例如电影海报的图片链接、电影名称等。
这是一个实现上述步骤的简单示例代码:
```python
from bs4 import BeautifulSoup
from urllib import request
url = "https://movie.douban.com/"
def get_html():
req = request.urlopen(url)
return req.read().decode('utf-8')
def get_movie_list(html):
soup = BeautifulSoup(html, 'lxml')
movie_list = soup.find('div', 'list-wp')
return movie_list
if __name__ == "__main__":
html = get_html()
movie_list = get_movie_list(html)
print(movie_list)
```
相关问题
python爬取豆瓣电影海报导演
### 使用Python从豆瓣网爬取电影海报图片和导演数据
为了实现这一目标,可以采用`requests`库发送HTTP请求并接收响应,再利用`BeautifulSoup`解析HTML文档提取所需的信息。下面展示一段用于获取单页内所有电影的海报链接及导演名字的方法。
```python
import requests
from bs4 import BeautifulSoup
def fetch_movie_info(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
items = []
for item in soup.select('div.item'):
poster_url = item.find('img')['src']
director_name = item.select_one('.bd p').get_text().split('\n')[1].strip().split('/')[0]
items.append((poster_url, director_name))
return items
```
此函数会返回一个列表,其中包含了每部影片对应的元组,每个元组里存储着该片的封面图URL地址以及其创作者姓名[^1]。
对于多页面的情况,则需构建循环机制遍历各个分页链接,从而收集完整的资料集。考虑到反爬虫策略的存在,在连续访问不同网页之间加入适当的时间间隔是有必要的,这可以通过调用`time.sleep()`方法来达成目的[^3]。
最后,如果希望保存所获得的图像文件到本地磁盘上,可借助于如下所示的小段代码:
```python
for idx, info in enumerate(items, start=1):
img_data = requests.get(info[0]).content
with open(f'./posters/{idx}.jpg', 'wb') as handler:
handler.write(img_data)
print("Download completed.")
```
上述操作能够确保下载下来的每一幅画作都被赋予独一无二的名字,并存放在指定路径下以便后续查阅或进一步处理[^2]。
帮我写一个完整的python爬取豆瓣top100电影的海报的完整代码
在Python中,我们可以使用requests库来获取网页内容,然后BeautifulSoup库解析HTML并提取我们需要的数据,最后使用`urllib.request.urlretrieve`保存图片到本地。这里是一个简单的示例,用于爬取豆瓣Top100电影的海报链接:
```python
import requests
from bs4 import BeautifulSoup
import os
# 豆瓣Top100电影URL
url = "https://movie.douban.com/top250"
def download_image(title, img_url):
# 定义保存路径,如果文件夹不存在就创建
save_path = f"images/{title}.jpg"
if not os.path.exists("images"):
os.makedirs("images")
try:
response = requests.get(img_url, stream=True)
response.raise_for_status() # 检查请求是否成功
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
print(f"海报下载完成: {save_path}")
except Exception as e:
print(f"下载失败: {e}")
def main():
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
# 解析电影标题及海报链接
movie_containers = soup.find_all('div', class_='hd')
for container in movie_containers:
title = container.find('span', itemprop='name').text.strip()
img_url = container.find('img', alt=True)['src']
# 下载海报
download_image(title, img_url)
if __name__ == "__main__":
main()
```
阅读全文
相关推荐















