Python 抓取html所有特定元素的方法
直接上代码哦,够直接了吧~
from lxml import etree #import mechanize import lxml.html #import cookielib #br = mechanize.Browser() #r = br.open('http://yourdomain.com') #html = br.response().read() #root = lxml.html.fromstring(html) #divs = root.xpath("//div[@class='test']") hparser = etree.HTMLParser(encoding='utf-8') #for avoiding unicode codec problems htree = etree.parse('http://yourdomain.com',hparser) htree.write('/tmp/bi.html') divs= htree.xpath("//div[@class='test']")
要获取class包含test的所有div,比如<div class="test website"></div>
把上述xpath的参数修改为 "div[contains(@class,'test')]" 即可。