我现在正在写一个脚本,把一个url带到lyricswikia,然后把歌词从网站上拉下来。我想我已经知道了如何隔离相关的div标签,但是出于某种原因,python在div标签前会输出一个"b'“,而我不知道如何从div标签内的脚本之间提取歌词。我的代码如下:
from bs4 import BeautifulSoup
import requests
#gets webpage
r = requests.get('http://lyrics.wikia.com/2Pac:Dear_Mama')
string = r.content
soup = BeautifulSoup(string[3:])
results = soup.find('div', {'class': 'lyricbox'}).encode('utf-8')
print(results)编辑:我的最终目标仍然是打印歌词,只打印网页上的歌词,作为字符串,所以我需要将字节文字对象转换为字符串,并以某种方式删除结尾的注释。我尝试从文森的建议代码中删除.encode('utf-8'),它可以工作,但它在注释末尾的开头显示一个错误。
发布于 2014-10-30 17:22:46
b,在https://docs.python.org/2/reference/lexical_analysis.html#string-literals之后
'b‘或'B’的前缀在Python2中被忽略;它指示文字在Python3中应该成为字节文字(例如,当代码自动转换为2to3时)。'u‘或'b’前缀后面可以跟'r‘前缀。
或者对于python 3 https://docs.python.org/3.3/reference/lexical_analysis.html#string-literals:
字节量总是以'b‘或’B‘为前缀;它们会生成一个字节类型的实例,而不是
类型。
使用Python2或Python3,这将打印出整个lyrik。
from __future__ import print_function
from bs4 import BeautifulSoup
import requests
#gets webpage
r = requests.get('http://lyrics.wikia.com/2Pac:Dear_Mama')
soup = BeautifulSoup(r.text)
for child in soup.select('div.lyricbox')[0].children:
if child.name == None:
print(child.encode('utf-8'))注:结尾处还有一些评论。
发布于 2014-10-31 06:22:39
如果你只需要歌词文本,我会建议使用pyquery而不是BeautifulSoup,因为我发现前者在许多情况下更容易使用。( BS在某些情况下表现出色,但这不一定是其中之一。)
import requests
from pyquery import PyQuery as pq
r = requests.get('http://lyrics.wikia.com/2Pac:Dear_Mama')
# You could also use r.content but it does not affect the result
doc = pq(r.text)
# Remove the script element; the HTML comment is ignored using .text()
print(doc('div.lyricbox').remove('script').text())更新:我刚刚注意到它被标记为Python3,目前我还没有一个测试用的盒子,但我假设它应该可以正常工作(我在最后一行更改了print() )。
https://stackoverflow.com/questions/26648888
复制相似问题