博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Xpath基本使用
阅读量:2055 次
发布时间:2019-04-28

本文共 933 字,大约阅读时间需要 3 分钟。

1.导入所需库

import requestsfrom lxml import etree

2.使用ruquests解析网页

def get_page(url):    try:        headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"} res = requests.get(url=url, headers=headers) res.encoding = 'utf-8' if res.status_code == 200: return res.text else: return None except Exception: return None

3.提取内容

if __name__ == '__main__':    url = 'https://www.*****.com/case/'    res = get_one_page(url)    tree = etree.HTML(res)    cons = tree.xpath('//div[@id="case_list"]/div')  # 返回case_list下所有div    con = tree.xpath('//div[@id="case_list"]/div[1]')  # 返回case_list下第一个div    con1 = tree.xpath('//div[@id="case_list"]/div[1]/div/a/@href')  # 返回case_list下第一个div下div下a的属性值    for con in cons:        href = con.xpath('./div/a/@href')  # ./表示当前标签        print(href)

转载地址:http://zwclf.baihongyu.com/

你可能感兴趣的文章
(PAT 1115) Counting Nodes in a BST (二叉查找树-统计指定层元素个数)
查看>>
(PAT 1143) Lowest Common Ancestor (二叉查找树的LCA)
查看>>
(PAT 1061) Dating (字符串处理)
查看>>
(PAT 1118) Birds in Forest (并查集)
查看>>
数据结构 拓扑排序
查看>>
(PAT 1040) Longest Symmetric String (DP-最长回文子串)
查看>>
(PAT 1145) Hashing - Average Search Time (哈希表冲突处理)
查看>>
(1129) Recommendation System 排序
查看>>
PAT1090 Highest Price in Supply Chain 树DFS
查看>>
(PAT 1096) Consecutive Factors (质因子分解)
查看>>
(PAT 1019) General Palindromic Number (进制转换)
查看>>
(PAT 1073) Scientific Notation (字符串模拟题)
查看>>
(PAT 1080) Graduate Admission (排序)
查看>>
Play on Words UVA - 10129 (欧拉路径)
查看>>
mininet+floodlight搭建sdn环境并创建简答topo
查看>>
【UML】《Theach yourself uml in 24hours》——hour2&hour3
查看>>
【linux】nohup和&的作用
查看>>
【UML】《Theach yourself uml in 24hours》——hour4
查看>>
Set、WeakSet、Map以及WeakMap结构基本知识点
查看>>
【NLP学习笔记】(一)Gensim基本使用方法
查看>>