写个爬取小破站各个分类的热门标签来简单地练习下xpath定位。(小小小练习~)
-
常用
- etree.HTML(text):调用HTML类对HTML文本进行初始化,成功构造XPath解析对象。会自动加上html和body元素(如果原字符串没有的话。返回Element类。
- etree.tostring(html):使用tostring可以提取出xml中所含的全部文本 。
- fromstring(some_xml_data):fromstring函数可以把一串xml解析为一个xml元素。返回Element类。
- etree.XML(“data”):XML函数的行为基本和fromstring一致。返回Element类。
- 辅助插件:
谷歌浏览器插件xpath helper
1.导入库
# -*- coding: utf-8 -*-
import requests
from lxml import etree
2.代码
xpath_practice():
def __init__(self):
self.url = 'https://www.bilibili.com/'
self.headers = {
# 添加请求头
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36 Edg/86.0.622.68"