python - 在Python中使用HTMLParser解析html中的特定链接?

标签 python html parsing

我正在尝试从 html 文件解析一组特定的链接,但由于我使用 HTMLParser,我无法访问层次结构树中的 html 信息,因此无法提取信息。

我的 HTML 如下:

<p class="mediatitle">
        <a class="bullet medialink" href="link/to/a/file">Some Content
        </a>
</p>

所以我需要的是提取所有其键为“href”且前一个属性为 class="bullet medialink"的值。换句话说,我只想要存在于“bullet medialink”类标签中的 thode href

到目前为止我尝试过的是

from HTMLParser import HTMLParser
import urllib
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
    if(tag == 'a'):
        for (key,value) in attrs:
            if(value == 'bullet medialink'):
                print "attr:", key

p = MyHTMLParser()
f = urllib.urlopen("sample.html")
html = f.read()
p.feed(html)
p.close()

最佳答案

为此我想要 Bs4。 Bs4 是第三方 html 解析器。文档:http://www.crummy.com/software/BeautifulSoup/bs4/doc/

import urllib
from bs4 import BeautifulSoup

f = urllib.urlopen("sample.html")
html = f.read()
soup = BeautifulSoup(html)
for atag in soup.select('.bullet.medialink'):  # Just enter a css-selector here
    print atag['href']  # You can also get an atrriibute with atag.get('href')

或更短:

import urllib
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib.urlopen("sample.html").read())
for atag in soup.select('.bullet.medialink'):
    print atag

关于python - 在Python中使用HTMLParser解析html中的特定链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374846/

相关文章:

html - 如何在 Jumbotron 上具体定位按钮?

javascript - Javascript游戏的问题

python - 检查当前行中的所有列值是否小于 Pandas 数据框中的前一行

python - Python Pandas 中的 Groupby/Sum - 零计数不显示......有时

python - 使用 "ptvsd"运行远程调试时出错

android - 我将数据解析到一个 ListView 中,现在如何将图像添加到每一行的左侧? (来自可绘制文件夹)

c++ - Boost Spirit Parser 使用三个字符串的 vector 编译成一个结构,适应不工作

python - 在 python 中导入 VLC 模块时出现属性错误

javascript - 有什么方法可以在 Flash 中显示 HTML 内容吗?

c - 在 C 中解析文件中的指令的简单方法?