# 获取电影名称 title = item.find('div', attrs={'class': 'hd'}).find('a').text # 获取电影名称 title = title.split('/') name = '' for i in title: i = i.replace('\n', '').replace('\xa0', '') i = i.strip() name += i + '/'这是爬取豆瓣t205的数据代码,请帮我修改一下,比如在url为https://movie.douban.com/top250?start={}&filter=的网站爬取的信息为'肖申克的救赎',而不是'肖申克的救赎/The Shawshank Redemption/月黑高飞(港)/刺激1995(台)'
时间: 2024-01-17 16:04:07 浏览: 27
您可以通过修改获取电影名称的代码来获取您需要的信息,具体方法如下:
```python
title = item.find('div', attrs={'class': 'hd'}).find('a').text # 获取电影名称
title = title.split('/')[0] # 只获取第一个/之前的部分
title = title.replace('\n', '').replace('\xa0', '').strip() # 去除空格和换行符
name = title # 将修改后的名称存储在变量name中
```
这样,您就可以获取到电影的名称为“肖申克的救赎”,而不是包含其他信息的完整标题。
相关问题
ul = bs.find("div",attrs={"class":"nav-con"})
ul = bs.find("div", attrs={"class":"nav-con"})是通过BeautifulSoup库中的find方法,在bs对象上查找标签为div,属性为class为nav-con的元素。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Python 实现简单的爬虫](https://blog.csdn.net/zihong522/article/details/122348086)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
import requests from bs4 import BeautifulSoup url = "https://www.dpm.org.cn/lights/royal/p/1.html" #代码开始 r=requests.get(url) r.encoding='utf-8' soup=BeautifulSoup(r.text,'html.parser') pics=soup.find_all("div",class_="pic") xh=1 for pic in pics: x=pic.find("img") imglj=x.attrs["src"] imgmz=x.attrs["title"].strip() #代码开始 r=requests.get(imglj) cpmc="image//"+imgmz+".jpg" f1=open(cpmc,"bw") f1.write(r.content) f1.close() xh+=1 报错 No such file or directory: 'image//清 沈全沈世杰沈世儒合笔婴戏图贴落.jpg'
这段代码报错是因为尝试在不存在的目录下创建文件。可以先在程序中加入一个创建目录的函数,如下所示:
```python
import os
def mkdir(path):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
url = "https://www.dpm.org.cn/lights/royal/p/1.html"
r=requests.get(url)
r.encoding='utf-8'
soup=BeautifulSoup(r.text,'html.parser')
pics=soup.find_all("div",class_="pic")
xh=1
mkdir("image") # 创建目录
for pic in pics:
x=pic.find("img")
imglj=x.attrs["src"]
imgmz=x.attrs["title"].strip()
r=requests.get(imglj)
cpmc="image/"+imgmz+".jpg" # 修改文件路径
f1=open(cpmc,"bw")
f1.write(r.content)
f1.close()
xh+=1
```
这样就能够在程序所在目录下创建一个名为 `image` 的目录,并在其中存储下载的图片了。