我知道BeautifulSoup是规范的HTML解析模块,但是有时您只想从某些HTML中抓取一些子字符串,而pyparsing有一些有用的方法可以做到这一点。使用此代码:
from pyparsing import makeHTMLTags, withAttribute, SkipToimport urllib# get the HTML from your URLurl = "http://www.whitecase.com/Attorneys/List.aspx?LastName=&FirstName="page = urllib.urlopen(url)html = page.read()page.close()# define opening and closing tag expressions for <td> and <a> tags# (makeHTMLTags also comprehends tag variations, including attributes, # upper/lower case, etc.)tdStart,tdEnd = makeHTMLTags("td")aStart,aEnd = makeHTMLTags("a")# only interested in tdStarts if they have "class=altRow" attributetdStart.setParseAction(withAttribute(("class","altRow")))# compose total matching pattern (add trailing tdStart to filter out # extraneous <td> matches)patt = tdStart + aStart("a") + SkipTo(aEnd)("text") + aEnd + tdEnd + tdStart# scan input HTML source for matching refs, and print out the text and # href valuesfor ref,s,e in patt.scanString(html): print ref.text, ref.a.href我从您的页面中提取了914条引用,从Abel到Zupikova。
Abel, Christian /cabelAcevedo, Linda Jeannine /jacevedoAcuña, Jennifer /jacunaAdeyemi, Ike /igbadegesinAdler, Avraham /aadler...Zhu, Jie /jzhuZÃdek, AleÅ¡ /azidekZiółek, Agnieszka /aziolekZitter, Adam /azitterZupikova, Jana /jzupikova



