我正在尝试从 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/