注册 登录
编程论坛 Python论坛

求大神解答一下爬虫的时候如何读取一个标签里面的一段文字呢?

LanXX 发布于 2019-12-24 14:33, 1642 次点击
按下面的方法会把又名也爬下来,因为<a>元素里面里面还有一个<span>,怎么可以只爬出专辑的名字,不把专辑名后面的部分爬下来呢?求大神解答一下,十分感谢!!

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48'}
url = 'https://music.'

res = requests.get(url,headers = headers)
print(res.status_code)

html = res.text
soup = BeautifulSoup(html, 'html.parser')
tags = soup.find_all('div',class_='pl2')

for tag in tags:
    title = tag.find('a').text.strip()
    print(title)
1 回复
#2
wp2319572019-12-24 15:23
回复 楼主 LanXX
程序代码:

for tag in tags:
    title = tag.find('a').contents[0].string.strip()
    print(title)
1