使用Python从解析的HTML中提取文本 [英] Extracting Text from Parsed HTML with Python

查看:132
本文介绍了使用Python从解析的HTML中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我一直在尝试使用经过BeautifulSoup解析的正则表达式搜索html.我没有取得任何成功,我认为原因是我不完全了解如何正确设置正则表达式.我已经看过有关类似问题的较早问题,但我仍然没有弄清楚.如果有人可以提取"/torrent/32726/0/"和"Slackware Linux 13.0 [x86 DVD ISO]"以及正则表达式的详细表达方式,那将非常有帮助.

I'm new to Python and I have been trying to search through html with regular expressions that has been parsed with BeautifulSoup. I haven't had any success and I think the reason is that I don't completely understand how to set up the regular expressions properly. I've looked at older questions about similar problems but I still haven't figured it out. If somebody could extract the "/torrent/32726/0/" and "Slackware Linux 13.0 [x86 DVD ISO]" as well as a detailed expression of how the regular expression works, it would be really helpful.

<td class="name">
  <a href="/torrent/32726/0/">
   Slackware Linux 13.0 [x86 DVD ISO]
  </a>
 </td>

我的意思是,我正在尝试使用BeautifulSoups函数提取"/torrent/32726/0/"和"Slackware Linux 13.0 [x86 DVD ISO]",以搜索语法分析树.在搜索和阅读文档之后,我一直在尝试各种事情,但是我仍然不确定如何去做.

What I meant to say is, I am trying to extract "/torrent/32726/0/" and "Slackware Linux 13.0 [x86 DVD ISO]" using BeautifulSoups functions to search the parse tree. I've been trying various things after searching and reading the documentation, but I'm still not sure on how to go about it.

推荐答案

BeautifulSoup还可以从您的html中提取节点值.

BeautifulSoup could also extract node values from your html.

from BeautifulSoup import BeautifulSoup

html = ('<html><head><title>Page title</title></head>'
       '<body>'
       '<table><tr>'
       '<td class="name"><a href="/torrent/32726/0/">Slackware Linux 13.0 [x86 DVD ISO]</a></td>'
       '<td class="name"><a href="/torrent/32727/0/">Slackware Linux 14.0 [x86 DVD ISO]</a></td>'
       '<td class="name"><a href="/torrent/32728/0/">Slackware Linux 15.0 [x86 DVD ISO]</a></td>'
       '</tr></table>'
       'body'
       '</html>')
soup = BeautifulSoup(html)
links = [td.find('a') for td in soup.findAll('td', { "class" : "name" })]
for link in links:
    print link.string

输出:

Slackware Linux 13.0 [x86 DVD ISO]  
Slackware Linux 14.0 [x86 DVD ISO]  
Slackware Linux 15.0 [x86 DVD ISO]  

这篇关于使用Python从解析的HTML中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆