Vis*_*man 0 html python parsing
我有这个小班:
class HTMLTagStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, data):
self.fed.append(data)
def handle_starttag(self, tag, attrs):
if tag == 'a':
return attrs[0][1]
def get_data(self):
return ''.join(self.fed)
Run Code Online (Sandbox Code Playgroud)
解析此HTML代码:
<div id="footer">
<p>long text.</p>
<p>click <a href="somelink.com">here</a>
</div>
Run Code Online (Sandbox Code Playgroud)
这是我得到的结果:long text click here
但我想得到:long text click somelink.com
有没有办法做到这一点?
看看BeautifulSoup ..它会做到这一点以及更多.
或者您可以使用正则表达式/字符串操作来去除所需的数据.从长远来看,使用像BeautifulSoup这样的东西会有所回报,特别是如果你希望做更多的事情.
这是使用BeautifulSoup提取HTML数据中单/唯一链接的一种方法(我不是这方面的专家,所以可能有其他更好的方法 - 建议/更正欢迎).
from BeautifulSoup import BeautifulSoup
s = """<div id="footer">
<p>long text.</p>
<p>click <a href="somelink.com">here</a>
</div>"""
soup = BeautifulSoup(s)
your_link = soup.find('a', href=True)['href']
print 'long text click', your_link
Run Code Online (Sandbox Code Playgroud)
将打印:
long text click somelink.com
| 归档时间: |
|
| 查看次数: |
422 次 |
| 最近记录: |