[英]HTML text extraction
我有一个清单,来自美丽汤。
soup = BeautifulSoup(page.content, 'html.parser')
area = soup.select("td strong")
例如
area=[
<strong><span style="font-size:1.4em;">120 Beats Per Minute (15)</span><br/><br/>Cinema</strong>,
<strong><span style="font-size:1.4em;">A Little Night Music</span><br/><br/>Theatre</strong>,
<strong><span style="font-size:1.4em;">A Wrinkle in Time (PG)</span><br/><br/>Cinema</strong>
]
除了电影院,剧院之外,我需要摆脱文本。
我想出了下面的表达式,但无法将其应用于列表
x[x.find('<br/><br/>')+10:].replace('</strong>','')
有什么想法可以应用此表达式从列表中提取数据以创建新列表吗? 我已经试过了:
clean_area=[]
for x in area:
clean_area.append(x[x.find('<br/><br/>')+10:].replace('</strong>',''))
但我收到此错误:TypeError:+不支持的操作数类型:'NoneType'和'int'
大约一个小时前,我正在回答您的第一篇文章,但您将其删除了。
我不确定这是否是最好的方法,但这是我想出的:
text = [
"""<strong><span style="font-size:1.4em;">120 Beats Per Minute (15)</span><br/><br/>Cinema</strong>""",
"""<strong><span style="font-size:1.4em;">A Little Night Music</span><br/><br/>Theatre</strong>""",
"""<strong><span style="font-size:1.4em;">A Wrinkle in Time (PG)</span><br/><br/>Cinema</strong>"""
]
text = ''.join(text) #Converting list of strings to one string
start = "<br/><br/>" #Start indication
end = "</" #End indication
clean_area = []
index = 0
while index < len(text):
index = text.find(start, index)
if index == -1:
break
clean_area.append(text[index+len(start):text.find(end, index)])
index += len(start)
print(clean_area)
您要使用的是decompose
这将删除您不需要的所有标签。
在这种情况下是span
所以
for x in soup.findAll("span"):
x.decompose()
print(soup.text)
回报
Cinema, Theatre
我只能使用2个通行证才能使用此功能。 我敢肯定这不是最好的方法,但至少有效。
soup = BeautifulSoup(result.content, "html.parser")
for x in soup.findAll("span"):
x.decompose()
area = soup.select("td strong")
a = str(area)
soup2 = BeautifulSoup(a)
tr = []
for tag in soup2.find_all(True):
tr.append(tag.text)
clean_area = []
for i in tr[::3]:
clean_area.append(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.