标签:hello attr www world str 文档 get classname ext2
myPage = ‘‘‘<html>html = etree.fromstring(myPage)
#一、定位
divs1 = html.xpath(‘//div‘)
divs2 = html.xpath(‘//div[@id]‘)
divs3 = html.xpath(‘//div[@class="foot"]‘)
divs4 = html.xpath(‘//div[@]‘)
divs5 = html.xpath(‘//div[1]‘)
divs6 = html.xpath(‘//div[last()-1]‘)
divs7 = html.xpath(‘//div[position()<3]‘)
divs8 = html.xpath(‘//div|//h1‘)
divs9 = html.xpath(‘//div[not(@)]‘)
text1 = html.xpath(‘//div/text()‘)
text2 = html.xpath(‘//div[@id]/text()‘)
text3 = html.xpath(‘//div[@class="foot"]/text()‘)
text4 = html.xpath(‘//div[@*]/text()‘)
text5 = html.xpath(‘//div[1]/text()‘)
text6 = html.xpath(‘//div[last()-1]/text()‘)
text7 = html.xpath(‘//div[position()<3]/text()‘)
text8 = html.xpath(‘//div/text()|//h1/text()‘)
#三、取属性 @
value1 = html.xpath(‘//a/@href‘)
value2 = html.xpath(‘//img/@src‘)
value3 = html.xpath(‘//div[2]/span/@id‘)
#四、定位(进阶)
#1.文档(DOM)元素(Element)的find,findall方法
divs = html.xpath(‘//div[position()<3]‘)
for div in divs:
ass = div.findall(‘a‘) # 这里只能找到:div->a, 找不到:div->p->a
for a in ass:
if a is not None:
#print(dir(a))
print(a.text, a.attrib.get(‘href‘)) #文档(DOM)元素(Element)的属性:text, attrib
a_href = html.xpath(‘//div[position()<3]/a/@href‘)
print(a_href)
#3.注意与1、2的区别
a_href = html.xpath(‘//div[position()<3]//a/@href‘)
print(a_href)
参考:https://www.cnblogs.com/hhh5460/p/5079465.html
标签:hello attr www world str 文档 get classname ext2
原文地址:http://blog.51cto.com/13831593/2296394