Python学习之解析HTML文档
1. xpath 解析
1.1 直接通过xpath获取元素
\# pip install lxml
from lxml import etree
import requests
\# get 请求
res = requests.get(url,headers=headers)
\# 判断请求的状态
if res.status_code ==200 :
\# 获取响应的数据
response = res.content.decode('utf-8')
res_html = etree.HTML(response)
ips = res_html.xpath('//table[@id="ip_list"]//tr//td[2]//text()')
ports = res_html.xpath('//table[@id="ip_list"]//tr//td[3]//text()')
通过标签 ‘//标签名’ @class=xxx @id=xxx 来获取元素 对HTML Dom树中去取 ,结果是一个集合
2.BeautifulSoup 解析
2.1 fand_all – select 获取元素
\#导包
import requests
from bs4 import BeautifulSoup
\# 解析html find_all 查找元素数据
soup = BeautifulSoup(response, '