1.XPath的使用 用来解析XML,
也可以用来解析HTML。同Beautiful Soup一样,在XPath中提供了非常简洁的节点选择的方法,Beautiful Soup主要是通过.的方式来进行子节点或者子孙节点的选择,而在XPath中则主要通过/的方式来选择节点。
2.etree.HTML(response.text),使用etree模块中的HTML类来对百度html(response.text)进行初始化以构造XPath解析对象,返回的类型为lxml.etree._Element etree.tostring(bd_html_elem).decode("utf-8"),将上述对象转化为字符串类型且编码为utf-8 html.unescape(bd_html),使用HTML5标准定义的规则将bd_html转换成对应unicode字符
实现步骤如下:
from lxml import etree
import requests
import html
response=requests.get("http://www.baidu.com")
encoding=response.apparent_encoding
response.encoding=encoding
# print(response.text)
bd_bj=etree.HTML(response.text)
img_href_ls=bd_bj.xpath("//img/@src")
img_href=bd_bj.xpath("//div[@id='lg']/img[@hidefocus='true']/@src")
a_content_ls=bd_bj.xpath("//a//text()")
a_news_content=bd_bj.xpath("//a[@class='mnav' and @name='tj_trnews']/text()")
print(img_href_ls)
print(img_href)
print(a_content_ls)
print(a_news_content)
展示结果: