用python写一段爬取音乐的代码
时间: 2024-02-18 11:52:28 浏览: 25
好的,这是一段爬取音乐的简单代码:
```
import requests
url = 'https://www.example.com/music.mp3'
response = requests.get(url)
with open('music.mp3', 'wb') as f:
f.write(response.content)
print('Music downloaded successfully!')
```
这段代码使用了 `requests` 库,通过向音乐文件的 URL 发送请求,并将响应内容写入本地文件,从而实现爬取音乐的目的。请注意,这仅仅是一个示例代码,您需要根据实际情况修改 URL 和文件名称。
相关问题
用python写一段爬取网页数据的代码
好的,以下是一个简单的Python爬虫实例,可以爬取指定网页的HTML代码:
```python
import requests
url = 'https://www.example.com' # 指定要爬取的网址
response = requests.get(url) # 发送GET请求获取网页内容
html = response.text # 获取网页HTML代码
print(html) # 打印HTML代码
```
需要注意的是,爬虫可能会涉及到法律和道德方面的问题,请在使用爬虫时遵守相关规定。同时,爬虫也可能会对网站造成一定的负担和影响,建议在爬取前先咨询网站管理员或所有者的意见。
用python写一段爬取百度图片的代码
以下是一段用 Python 爬取百度图片的代码:
```python
import requests
import re
import os
def get_image(keyword):
url = 'https://image.baidu.com/search/index?tn=baiduimage&word=' + keyword
html = requests.get(url).text
pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
i = 1
for each in pic_url:
print(each)
try:
pic = requests.get(each, timeout=10)
except requests.exceptions.ConnectionError:
print('【错误】当前图片无法下载')
continue
string = 'pictures/' + keyword + '_' + str(i) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
i += 1
if __name__ == '__main__':
if not os.path.exists('pictures'):
os.mkdir('pictures')
get_image('猫')
```
这段代码可以爬取百度图片中关键词为“猫”的图片,并保存在本地的“pictures”文件夹中。