注册 登录
编程论坛 Python论坛

pycharm的一个问题

QQ3172973615 发布于 2021-04-16 20:42, 1636 次点击
麻烦各位看看,是怎么回事,该怎么办,谢谢
程序代码:
url = 'https://music.'
base_url = 'https://music.'
a = input('请输入歌单的ID:')
file = "C:/Users/Administrator/PycharmProjects/pythonProject1/网易云音乐/"  # 保存音乐的文件路径,最后加斜杠
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}
wurl = "https://link."# 要下载歌曲的ID
playlist_url = url+a
music = requests.get(playlist_url, headers=headers).text
html_dom = etree.HTML(music)
song_ids = html_dom.xpath('//a[contains(@href,"song?")]/@href')
for data in song_ids:
    print(data)
    href = data.xpath('//a/@href')[0]
    music_id = href.split("=")[1]
    music_id =html_dom.xpath("//href/text()")
    wang_url = "https://music." + music_id
    song_url = wurl + music_id + ".mp3"

然后就报错了:
/song?id=${song.id}
Traceback (most recent call last):
  File "C:/Users/Administrator/AppData/Roaming/JetBrains/PyCharmCE2021.1/scratches/scratch.py", line 17, in <module>
    href = data.xpath('//a/@href')[0]
AttributeError: 'lxml.etree._ElementUnicodeResult' object has no attribute 'xpath'

Process finished with exit code 1
大家看看该如何修改,麻烦了
1 回复
#2
_xXx_2021-09-05 20:30
没用过lxml,看保存你那个 data 已经变成 lxml.etree._ElementUnicodeResult 对象了,说白了就是这个对象没有xpath方法,你把它当成html_dom一类对象直接用了,需要转化一下。没用过lxml,如有说错见谅,建议还得直接用Beautiful Soup吧
1