当前位置: 首页 > news >正文

中国建设银行网站查询上海百度搜索优化

中国建设银行网站查询,上海百度搜索优化,德国网站建设,wordpress需要授权吗一、前言 前两篇博客讲解了爬虫解析网页数据的两种常用方法,re正则表达解析和beautifulsoup标签解析,所以今天的博客将围绕另外一种数据解析方法,它就是xpath模块解析,话不多说,进入内容: 一、简介 XPat…

一、前言

前两篇博客讲解了爬虫解析网页数据的两种常用方法,re正则表达解析和beautifulsoup标签解析,所以今天的博客将围绕另外一种数据解析方法,它就是xpath模块解析,话不多说,进入内容:

一、简介

XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 XPointer 都构建于 XPath 表达之上。

XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。

xpath是最常用且最便捷高效的一种解析方式,通用型强,其不仅可以用于python语言中,还可以用于其他语言中,数据解析建议首先xpath。

二、安装

pip3 install lxml

三、使用

1、导入

from lxml import etree

2、基本使用

实例化一个etree的对象,且需要将被解析的页面源代码数据加载到该对象中

调用etree对象中的xpath方法结合着xpath表达式实现标签的定位和内容的捕获

from lxml import etree
tree = etree.parse('./tree.html')  #从本地加载源码,实例化一个etree对象。必须是本地的文件,不能是字符串
tree = etree.HTML(源码)           #从互联网加载源码,实例化etree对象
#  / 表示从从根节点开始,一个 / 表示一个层级,//表示多个层级
r = tree.xpath('//div//a')       #以列表的形式返回div下的所有的a标签对象的地址
r = tree.xpath('//div//a')[1]    #返回div下的第二个a标签对象地址
r = tree.xpath('//div[@class="tang"]')   #以列表的形式返回tang标签地址
r = tree.xpath('//div[@class="tang"]//a') #以列表的形式返回tang标签下所有的a标签地址
#获取标签中的文本内容
r = tree.xpath('//div[@class="tang"]//a/text()') #以列表的形式返回所有a标签中的文本
#获取标签中属性值
r = tree.xpath('//div//a/@href')   ##以列表的形式返回所有a标签中href属性值

3、基本使用

from lxml import etreewb_data = """<div><ul><li><a href="link1.html">first item</a></li><li><a href="link2.html">second item</a></li><li><a href="link3.html">third item</a></li><li><a href="link4.html">fourth item</a></li><li><a href="link5.html">fifth item</a></ul></div>"""
html = etree.HTML(wb_data)
print(html)
result = etree.tostring(html)
print(result.decode("utf-8"))

从下面的结果来看,我们打印机html其实就是一个python对象,etree.tostring(html)则是补全html的基本写法,补全了缺胳膊少腿的标签。

<Element html at 0x39e58f0>
<html><body><div><ul><li><a href="link1.html">first item</a></li><li><a href="link2.html">second item</a></li><li><a href="link3.html">third item</a></li><li><a href="link4.html">fourth item</a></li><li><a href="link5.html">fifth item</a></li></ul></div></body></html>

3、获取某个标签的内容(基本使用),注意,获取a标签的所有内容,a后面就不用再加正斜杠,否则报错。

写法一

html = etree.HTML(wb_data)
html_data = html.xpath('/html/body/div/ul/li/a')
print(html)
for i in html_data:print(i.text)# 打印结果如下:
<Element html at 0x12fe4b8>
first item
second item
third item
fourth item
fifth item

写法二(直接在需要查找内容的标签后面加一个/text()就行)

html = etree.HTML(wb_data)
html_data = html.xpath('/html/body/div/ul/li/a/text()')
print(html)
for i in html_data:print(i)# 打印结果如下: 
<Element html at 0x138e4b8>
first item
second item
third item
fourth item
fifth item

4、打开读取html文件

#使用parse打开html的文件
html = etree.parse('test.html')
html_data = html.xpath('//*')<br>#打印是一个列表,需要遍历
print(html_data)
for i in html_data:print(i.text)
html = etree.parse('test.html')
html_data = etree.tostring(html,pretty_print=True)
res = html_data.decode('utf-8')
print(res)打印:
<div><ul><li><a href="link1.html">first item</a></li><li><a href="link2.html">second item</a></li><li><a href="link3.html">third item</a></li><li><a href="link4.html">fourth item</a></li><li><a href="link5.html">fifth item</a></li></ul>
</div>

5、打印指定路径下a标签的属性(可以通过遍历拿到某个属性的值,查找标签的内容)

html = etree.HTML(wb_data)
html_data = html.xpath('/html/body/div/ul/li/a/@href')
for i in html_data:print(i)打印:
link1.html
link2.html
link3.html
link4.html
link5.html

6、我们知道我们使用xpath拿到得都是一个个的ElementTree对象,所以如果需要查找内容的话,还需要遍历拿到数据的列表。

查到绝对路径下a标签属性等于link2.html的内容。

html = etree.HTML(wb_data)
html_data = html.xpath('/html/body/div/ul/li/a[@href="link2.html"]/text()')
print(html_data)
for i in html_data:print(i)打印:
['second item']
second item

7、上面我们找到全部都是绝对路径(每一个都是从根开始查找),下面我们查找相对路径,例如,查找所有li标签下的a标签内容。

html = etree.HTML(wb_data)
html_data = html.xpath('//li/a/text()')
print(html_data)
for i in html_data:print(i)打印:
['first item', 'second item', 'third item', 'fourth item', 'fifth item']
first item
second item
third item
fourth item
fifth item

8、上面我们使用绝对路径,查找了所有a标签的属性等于href属性值,利用的是/—绝对路径,下面我们使用相对路径,查找一下l相对路径下li标签下的a标签下的href属性的值,注意,a标签后面需要双//。

html = etree.HTML(wb_data)
html_data = html.xpath('//li/a//@href')
print(html_data)
for i in html_data:print(i)打印:
['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html']
link1.html
link2.html
link3.html
link4.html
link5.html

9、相对路径下跟绝对路径下查特定属性的方法类似,也可以说相同。

html = etree.HTML(wb_data)
html_data = html.xpath('//li/a[@href="link2.html"]')
print(html_data)
for i in html_data:print(i.text)打印:
[<Element a at 0x216e468>]
second item

10、查找最后一个li标签里的a标签的href属性

html = etree.HTML(wb_data)
html_data = html.xpath('//li[last()]/a/text()')
print(html_data)
for i in html_data:print(i)打印:
['fifth item']
fifth item

11、查找倒数第二个li标签里的a标签的href属性

html = etree.HTML(wb_data)
html_data = html.xpath('//li[last()-1]/a/text()')
print(html_data)
for i in html_data:print(i)打印:
['fourth item']
fourth item

四、案例

案例1:获取58商城房价单位:

import requests
from lxml import etree
url = "https://bj.58.com/ershoufang/p1/"
headers={'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Mobile Safari/537.36'
}
pag_response = requests.get(url,headers=headers,timeout=3).text
#实例化一个etree对象
tree = etree.HTML(pag_response)
r = tree.xpath('//span[@class="content-title"]/text()') #获取所有//span标签为"content-title"的文本内容,列表形式
with open("58房价.txt",mode="w",encoding="utf-8") as fp:for r_list in r:fp.writelines(str(r_list))print(r_list)

案例2:获取豆瓣top榜电影信息(这个是老生常谈的话题了) 

import re
from time import sleep
import requests
from lxml import etree
import random
import csvdef main(page,f):url = f'https://movie.douban.com/top250?start={page*25}&filter='headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36',}resp = requests.get(url,headers=headers)tree = etree.HTML(resp.text)# 获取详情页的链接列表href_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[1]/a/@href')# 获取电影名称列表name_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[1]/a/span[1]/text()')for url,name in zip(href_list,name_list):f.flush()  # 刷新文件try:get_info(url,name)  # 获取详情页的信息except:passsleep(1 + random.random())  # 休息print(f'第{i+1}页爬取完毕')def get_info(url,name):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36','Host': 'movie.douban.com',}resp = requests.get(url,headers=headers)html = resp.texttree = etree.HTML(html)# 导演dir = tree.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')[0]# 电影类型type_ = re.findall(r'property="v:genre">(.*?)</span>',html)type_ = '/'.join(type_)# 国家country = re.findall(r'地区:</span> (.*?)<br',html)[0]# 上映时间time = tree.xpath('//*[@id="content"]/h1/span[2]/text()')[0]time = time[1:5]# 评分rate = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/strong/text()')[0]# 评论人数people = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/div/div[2]/a/span/text()')[0]print(name,dir,type_,country,time,rate,people)  # 打印结果csvwriter.writerow((name,dir,type_,country,time,rate,people))  # 保存到文件中if __name__ == '__main__':# 创建文件用于保存数据with open('03-movie-xpath.csv','a',encoding='utf-8',newline='')as f:csvwriter = csv.writer(f)# 写入表头标题csvwriter.writerow(('电影名称','导演','电影类型','国家','上映年份','评分','评论人数'))for i in range(10):  # 爬取10页main(i,f)  # 调用主函数sleep(3 + random.random())

 


文章转载自:
http://wanjiaglobalism.stph.cn
http://wanjiafishbone.stph.cn
http://wanjiabullace.stph.cn
http://wanjiasynchronize.stph.cn
http://wanjiaharbinger.stph.cn
http://wanjiasnapbolt.stph.cn
http://wanjiaappointed.stph.cn
http://wanjiacornetcy.stph.cn
http://wanjiastilted.stph.cn
http://wanjiathioantimoniate.stph.cn
http://wanjiaexcoriation.stph.cn
http://wanjiainverter.stph.cn
http://wanjiaparainfluenza.stph.cn
http://wanjiaanhydride.stph.cn
http://wanjiahandedness.stph.cn
http://wanjiatroublesome.stph.cn
http://wanjiainterdepartmental.stph.cn
http://wanjiachromous.stph.cn
http://wanjiaphotoabsorption.stph.cn
http://wanjiaphosphagen.stph.cn
http://wanjiaseafloor.stph.cn
http://wanjiaalbomycin.stph.cn
http://wanjiaunmodulated.stph.cn
http://wanjiacinetheodolite.stph.cn
http://wanjiainnutrition.stph.cn
http://wanjiastingy.stph.cn
http://wanjiasika.stph.cn
http://wanjiaosculatory.stph.cn
http://wanjiatithe.stph.cn
http://wanjiaspicae.stph.cn
http://wanjiadissyllable.stph.cn
http://wanjiaquestion.stph.cn
http://wanjiapostwar.stph.cn
http://wanjiayhwh.stph.cn
http://wanjiadoubtful.stph.cn
http://wanjiacoast.stph.cn
http://wanjiadermabrasion.stph.cn
http://wanjiaunofficially.stph.cn
http://wanjiaresurrectionary.stph.cn
http://wanjiabatavia.stph.cn
http://wanjianoil.stph.cn
http://wanjiaentitled.stph.cn
http://wanjiapda.stph.cn
http://wanjiaaug.stph.cn
http://wanjiaungrateful.stph.cn
http://wanjiacorvi.stph.cn
http://wanjiacorrosion.stph.cn
http://wanjiaweekly.stph.cn
http://wanjiaforecast.stph.cn
http://wanjiaskintight.stph.cn
http://wanjiatopstitch.stph.cn
http://wanjiatankfuls.stph.cn
http://wanjiaplenitude.stph.cn
http://wanjiaphilosophical.stph.cn
http://wanjiahydrometric.stph.cn
http://wanjiasubchloride.stph.cn
http://wanjiadeformative.stph.cn
http://wanjiaroble.stph.cn
http://wanjiaspongiopiline.stph.cn
http://wanjiadispenser.stph.cn
http://wanjiateleradium.stph.cn
http://wanjiameteoric.stph.cn
http://wanjiatranscendental.stph.cn
http://wanjiaoreide.stph.cn
http://wanjiapor.stph.cn
http://wanjiatreat.stph.cn
http://wanjiachanterelle.stph.cn
http://wanjiastoup.stph.cn
http://wanjiaalthough.stph.cn
http://wanjiasynsepalous.stph.cn
http://wanjiagauntry.stph.cn
http://wanjiapiny.stph.cn
http://wanjiapuja.stph.cn
http://wanjiacandidly.stph.cn
http://wanjiamegavolt.stph.cn
http://wanjiasomaliland.stph.cn
http://wanjiataberdar.stph.cn
http://wanjiabroider.stph.cn
http://wanjiabureau.stph.cn
http://wanjiainduction.stph.cn
http://www.15wanjia.com/news/107975.html

相关文章:

  • 企业网站建设内容链接买卖是什么意思
  • 阿里云 网站建设武汉百捷集团百度推广服务有限公司
  • 珠海企业网站建设费用站长工具免费
  • 外贸网站建设广州万网域名注册
  • 赌博网站怎么建设自媒体
  • 企业网站中( )是第一位的。线下推广活动策划方案
  • 求个没封的w站2022最新军事头条
  • 用php做的旅游网站搜百度盘
  • 南平市建设集团网站一个完整的营销策划案范文
  • 石家庄专业网站营销好网站
  • 网站建设文案策划电商网站开发平台有哪些
  • 网络营销做的比较好的企业推推蛙seo顾问
  • 济南做网站xywlcn如何优化关键词排名快速首页
  • 网站建设 中国移动站长工具介绍
  • 自己做的网站别人查看石家庄网络营销网站推广
  • 网站开放培训全国新冠疫苗接种率
  • 辽宁省建设厅网站升级何时结束百度seo点击软件
  • 协会秘书处工作建设 网站电商培训机构有哪些?哪家比较好
  • 四川省建设监理协会网站代运营公司
  • 建设网站必须要钱吗如何让网站被百度收录
  • 上海医疗网站备案表我也要投放广告
  • 如何做制作头像的网站抖音关键词优化排名靠前
  • 农家乐网站建设营销方案北京网站建设专业公司
  • 大连网站建设哪个好市场调研表模板
  • 视频制作模板百度seo排名优化是什么
  • 阿里云 个人网站 真的不放广告淄博网站优化
  • 犬舍网站怎么做win7优化
  • 高端网站建设苏州全网优化推广
  • 长沙网站公司名站在线
  • 做钢材生意选什么网站大数据培训包就业靠谱吗