pip install lxml
from lxml import etree2.找到想要解析的网页,使用谷歌浏览器或者edge打开网页,然后使用开发者工具找到元素位置 3.右键找到的元素,然后点击复制,选择复制,选择复制完整xpath完整路径 4.在浏览器网页控制台输入$x(‘刚刚复制的Xpath路径’),得到元素位置 5. 然后定位到找到需要的内容:firstChild:text 6.代码实例
$x(‘//*[@id=“page-hd”]/div[1]/div[2]/div[1]/div[2]/div/div/span’)
import requests
from lxml import etree
url = 'https://hanyu.baidu.com/s?wd=张艺兴经典语录&device=pc&from=home'
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
}
resp = requests.get(url, headers=headers)
tree = etree.HTML(resp.text)
name = tree.xpath('//*[@id="page-hd"]/div[1]/div[2]/div[1]/div[2]/div/div/span/text()')
print(name)



