1406598279 发表于 2021-3-13 18:49:00

python爬虫

我想问问这个网站的mp3怎么用python爬虫下载?

YunGuo 发表于 2021-3-14 13:58:20

哪个网站?

1406598279 发表于 2021-3-14 14:46:32

YunGuo 发表于 2021-3-14 13:58
哪个网站?

这个:
weixin.jiafenba.net/book/lesseons.action?b=ff80808163d2efe2016a28e59588310e#
记得在最前面加上http://

YunGuo 发表于 2021-3-14 15:19:31

本帖最后由 YunGuo 于 2021-3-14 17:07 编辑

1406598279 发表于 2021-3-14 14:46
这个:
weixin.jiafenba.net/book/lesseons.action?b=ff80808163d2efe2016a28e59588310e#
记得在最前面 ...

最简单的代码:
import requests
from lxml import etree

url = 'http://weixin.jiafenba.net/book/lesseons.action?b=ff80808163d2efe2016a28e59588310e#'
header = {'user-agent': 'Mozilla/5.0'}    # 定义user-agent伪装
res = requests.get(url, headers=header)    # 请求页面
sel = etree.HTML(res.text)   # 解析响应html
datas = sel.xpath('/html/body/ul/li')    # xpath获取所有li列表(datas是一个列表)
for data in datas:
    name = data.xpath('@tiptitle')    # 获取标题
    mp3_url = 'http://weixin.jiafenba.net' + data.xpath('@filename')    # 获取MP3资源链接并组合成完整url
    mp3_res = requests.get(mp3_url)    # 请求MP3资源
    with open(name + '.mp3', 'wb')as f:
      f.write(mp3_res.content)    # mp3_res响应的二进制数据保存为MP3
    print(f'{name}下载完成!')

1406598279 发表于 2021-3-14 15:30:15

YunGuo 发表于 2021-3-14 15:19
最简单的代码:

解释一下可以吗?

YunGuo 发表于 2021-3-14 17:22:02

本帖最后由 YunGuo 于 2021-3-14 17:23 编辑

1406598279 发表于 2021-3-14 15:30
解释一下可以吗?

都是爬虫很基础的使用。如果看不懂,那么你应该没学爬虫???我就给你简单注释一下吧。还有不懂的,建议你学完爬虫基础。
import requests
from lxml import etree

url = 'http://weixin.jiafenba.net/book/lesseons.action?b=ff80808163d2efe2016a28e59588310e#'
header = {'user-agent': 'Mozilla/5.0'}   # 定义user-agent伪装防止网站反爬
res = requests.get(url, headers=header)   # 请求页面
sel = etree.HTML(res.text)   # 解析res响应的文本数据
datas = sel.xpath('/html/body/ul/li')   # 获取所有li标签数据(datas是一个列表)
for data in datas:
    name = data.xpath('@tiptitle')   # 获取当前li标签中的title
    mp3_url = 'http://weixin.jiafenba.net' + data.xpath('@filename')   #获取当前li标签中的MP3资源链接,并组合成完整url
    mp3_res = requests.get(mp3_url)   #请求MP3资源
    with open(name + '.mp3', 'wb')as f:   
    # with open()as f:上下文管理器,open方法打开指定的文件,第一个参数是文件名,第二个参数wb是写入二进制数据模式,当文件不存在时自动创建
      f.write(mp3_res.content)   #将mp3_res响应的二进制数据写入
    print(f'{name}下载完成!')

1406598279 发表于 2021-3-14 19:46:26

YunGuo 发表于 2021-3-14 17:22
都是爬虫很基础的使用。如果看不懂,那么你应该没学爬虫???我就给你简单注释一下吧。还有不懂的,建 ...

特别感谢!!!

龙舞九天 发表于 2021-5-10 05:15:33

{:5_95:}
页: [1]
查看完整版本: python爬虫