代码如下:
# -*- coding: utf-8 -*
import requests,time
from lxml import etree
url='https://movie.douban.com/subject/1849031/?from=subject-page'
html=requests.get(url).text #此处获取html网页代码
s=etree.HTML(html) #此处获取html节点对象
film_name=s.xpath('//*[@id="content"]/h1/span[1]/text()')[0]
director=s.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')
directors=','.join(director)
actor=s.xpath('//*[@id="info"]/span[3]/span[2]/a/text()')
actors=','.join(actor)
cls=s.xpath('//*[@id="info"]/span[@property="v:genre"]/text()')
clss=','.join(cls)
print ('电影名:',film_name,'\n导演:',directors,'\n主演:',actors,'\n类型:',clss)
actor=s.xpath('normalize-space(//*[@id="info"]/span[3]/span[2]/a/text())')
print ('主演:',actor,' //','normalize-space()等同于[0]')
结果如下:
小结:
1、使用xpath拿到得都是一个个的节点对象,即列表,所以如果需要查找内容的话,还需要遍历拿到数据的列表;
2、也可用normalize-space()或加[0],两者都是取的第一个值,但normalize-space()会去掉转义字符;或用join()函数;
3、切记:浏览器复制xpath 不是完全可靠的,可以去网页源码看看是否这一层级。