正则表达式 re.findall 用法、元素定位方式Xpath总结、python操作json和csv(转)

1.正则 re.findall 的简单用法

https://www.cnblogs.com/xieshengsen/p/6727064.html

2.xpath定位总结

https://blog.csdn.net/hou_angela/article/details/80305828

3.python操作json和csv

https://www.cnblogs.com/onefine/p/10499337.html

目录

1、正则 re.findall 的简单用法

2.xpath定位总结

3.python操作json和csv

JSON

csv文件处理


1、正则 re.findall 的简单用法

正则 re.findall  的简单用法(返回string中所有与pattern相匹配的全部字串,返回形式为数组)
语法:

1

findall(pattern, string, flags=0)

import re

Python 正则表达式 re findall 方法能够以列表的形式返回能匹配的子串

# print (help(re.findall))
# print (dir(re.findall))

findall查找全部r标识代表后面是正则的语句

1

2

3

regular_v1 = re.findall(r"docs","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v1)

# ['docs']

符号^表示匹配以https开头的的字符串返回,

1

2

3

regular_v2 = re.findall(r"^https","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v2)

# ['https']

  

用$符号表示以html结尾的字符串返回,判断是否字符串结束的字符串

1

2

3

regular_v3 = re.findall(r"html$","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v3)

# ['html']

# [...]匹配括号中的其中一个字符

1

2

3

regular_v4 = re.findall(r"[t,w]h","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v4)

# ['th', 'wh']

“d”是正则语法规则用来匹配0到9之间的数返回列表

1

2

3

4

5

6

regular_v5 = re.findall(r"\d","https://docs.python.org/3/whatsnew/3.6.html")

regular_v6 = re.findall(r"\d\d\d","https://docs.python.org/3/whatsnew/3.6.html/1234")

print (regular_v5)

# ['3', '3', '6']

print (regular_v6)

# ['123']

小d表示取数字0-9,大D表示不要数字,也就是出了数字以外的内容返回

1

2

3

regular_v7 = re.findall(r"\D","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v7)

# ['h', 't', 't', 'p', 's', ':', '/', '/', 'd', 'o', 'c', 's', '.', 'p', 'y', 't', 'h', 'o', 'n', '.', 'o', 'r', 'g', '/', '/', 'w', 'h', 'a', 't', 's', 'n', 'e', 'w', '/', '.', '.', 'h', 't', 'm', 'l']

“w”在正则里面代表匹配从小写a到z,大写A到Z,数字0到9

1

2

3

regular_v8 = re.findall(r"\w","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v8)

#['h', 't', 't', 'p', 's', 'd', 'o', 'c', 's', 'p', 'y', 't', 'h', 'o', 'n', 'o', 'r', 'g', '3', 'w', 'h', 'a', 't', 's', 'n', 'e', 'w', '3', '6', 'h', 't', 'm', 'l']

“W”在正则里面代表匹配除了字母与数字以外的特殊符号

1

2

3

regular_v9 = re.findall(r"\W","https://docs.python.org/3/whatsnew/3.6.html")

print (regular_v9)

# [':', '/', '/', '.', '.', '/', '/', '/', '.', '.']

 

2.xpath定位总结

 

一.绝对路径(不要使用,除非已经使用了所有方式仍然无法定位)
方法:根据实际目录,逐层输写。
例子: find_element_by_xpath("/html/body/div[2]/form/span/input") #div[2]指第2个元素
二.相对路径(建议使用)

方法:首先找目录元素是否有”精准元素“即唯一能标识的属性,找到,则用此属性定位;

1. 通过元素本身的唯一属性定位

   方法:找到目标元素所在的”精准元素“即唯一标识属性,使用此属性定位

1.1 通过id属性定位
      例:find_element_by_xpath("//input[@id='input']")        #@后跟属性,可以是任何属性

1.2 通过name属性定位
      例:find_element_by_xpath("//div[@name='q']")

2. 通过上一级目录的唯一属性定位

    方法:目标元素没有唯一属性,则去找到与目标元素相近的上级目录中”唯一元素“作为起始位置,然后根据此相对位置逐层往子目录编写到目标位置

例:  find_element_by_xpath("//span[@id='input-container']/input") 

        find_element_by_xpath("//div[@id='hd']/form/span/input")

       find_element_by_xpath("//div[@name='q']/form/span/input")

3.  xpath做布尔逻辑运算
例子:find_element_by_xpath("//div[@id='hd' or @name='q']")
4. 双条件同时过滤
      find_element_by_xpath("//div[@id='hd'][@name='q'")

5.目录元素存在层级关系

 

例1: find_element_by_xpath("//ul[@class='app-list']/li[contains(@class,'safe')]/div")
 例2:定位上一层再定位目标元素(定位dl再定位dt)

find_element_by_xpath("//form[@id='J_login_form]/dl/dt/input[@id='J_password']")

 


 
6. 模糊定位

6.1 contains 方法(包含)

find_element_by_xpath("//a[contains(@name,'trnews')]")

6.2 start-with方法(以XX开头)

find_element_by_xpath("//a[start-with(@href,'http')]")

6.3 text方法

find_element_by_xpath("//a[contains(text(),'新闻')]")  查找超链接元素的文本内容

find_element_by_xpath("//*[text()='新闻']")  查找所有内容为退出二字的元素

注意:元素属性值有空格时,尽量不使用带空格,可用contains等其他方法,避开空格

 

3.python操作json和csv

 

JSON

JSON(JavaScript Object Notation, JS 对象标记)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
它基于ECMAScript(w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得JSON成为理想的数据交换语言。

JSON支持数据格式:

  • 对象(字典)。使用花括号。
  • 数组(列表)。使用方括号。
  • 整形、浮点型、布尔类型还有null类型。
  • 字符串类型(字符串必须要用双引号,不能用单引号)。

多个数据之间使用逗号分开。注:json本质上就是一个字符串。

JSON函数

使用JSON函数需要导入json库:import json

函数 描述
json.dumps 将Python对象编码成JSON字符串
json.loads 将已编码的JSON字符串解码为Python对象

另外:
json.dump()json.load()主要用来读写json文件函数。

字典和列表转JSON

import json

books = [
    {
        'title': 'Python基础',
        'price': '79.00'
    },
    {
        'title': 'Scrapy网络爬虫',
        'price': '56.00'
    }
]

json_str = json.dumps(books)
print('type: ', type(json_str))
print('json_str: ', json_str)
# 输出:
type:  
json_str:  [{"title": "Python\u57fa\u7840", "price": "79.00"}, {"title": "Scrapy\u7f51\u7edc\u722c\u866b", "price": "56.00"}]

注:因为json在dump的时候,只能存放ASCII的字符,因此会将中文进行转义,这时候我们可以使用ensure_ascii=False关闭这个特性。

更改之后:

json_str = json.dumps(books, ensure_ascii=False)
# 输出:
[{"title": "Python基础", "price": "79.00"}, {"title": "Scrapy网络爬虫", "price": "56.00"}]

注:Python中,只有基本数据类型才能转换成JSON格式的字符串,即:intfloatstrlistdicttuple

将json数据直接dump到文件中

常规方式:

import json

books = [
    {
        'title': 'Python基础',
        'price': '79.00'
    },
    {
        'title': 'Scrapy网络爬虫',
        'price': '56.00'
    }
]

json_str = json.dumps(books, ensure_ascii=False)

with open('books.json', 'w') as fp:
    fp.write(json_str)

打开books.json文件发现出现了乱码:

[{"title": "Python����", "price": "79.00"}, {"title": "Scrapy��������", "price": "56.00"}]

然后指定文件编码方式:

with open('books.json', 'w', encoding='utf8') as fp:
    fp.write(json_str)

重新打开books.json文件发现一切正常:

[{"title": "Python基础", "price": "79.00"}, {"title": "Scrapy网络爬虫", "price": "56.00"}]

json模块中除了dumps函数,还有一个dump函数,这个函数可以传入一个文件指针,直接将字符串dump到文件中。

import json

books = [
    {
        'title': 'Python基础',
        'price': '79.00'
    },
    {
        'title': 'Scrapy网络爬虫',
        'price': '56.00'
    }
]


with open('books.json', 'w', encoding='utf8') as fp:
    json.dump(books, fp)
# 输出:
[{"title": "Python\u57fa\u7840", "price": "79.00"}, {"title": "Scrapy\u7f51\u7edc\u722c\u866b", "price": "56.00"}]

关闭中文转义:

with open('books.json', 'w', encoding='utf8') as fp:
    json.dump(books, fp, ensure_ascii=False)
# 输出:
[{"title": "Python基础", "price": "79.00"}, {"title": "Scrapy网络爬虫", "price": "56.00"}]

将一个json字符串load成Python对象

import json

json_str = '[{"title": "Python基础", "price": "79.00"}, {"title": "Scrapy网络爬虫", "price": "56.00"}]'
books = json.loads(json_str)

print('type: ', type(books))
print('boos: ', books)
# 输出:
type:  
boos:  [{'title': 'Python基础', 'price': '79.00'}, {'title': 'Scrapy网络爬虫', 'price': '56.00'}]

直接从文件中读取json:

import json

# 注意指定文件编码方式
with open('books.json', 'r', encoding='utf8') as fp:
    json_str = json.load(fp)
    print(json_str)

# 输出:
[{'title': 'Python基础', 'price': '79.00'}, {'title': 'Scrapy网络爬虫', 'price': '56.00'}]

csv文件处理

读取csv文件

import csv

with open('stock.csv','r') as fp:
    reader = csv.reader(fp)
    titles = next(reader)
    for x in reader:
        print(x)

这样操作,以后获取数据的时候,就要通过下表来获取数据。如果想要在获取数据的时候通过标题来获取。那么可以使用DictReader:

import csv

with open('stock.csv','r') as fp:
    reader = csv.DictReader(fp)
    for x in reader:
        print(x['turnoverVol'])

写入数据到csv文件

写入数据到csv文件,需要创建一个writer对象,主要用到两个方法。一个是writerow,这个是写入一行。一个是writerows,这个是写入多行:

import csv

headers = ['name','age','classroom']
values = [
    ('zhiliao',18,'111'),
    ('wena',20,'222'),
    ('bbc',21,'111')
]
with open('test.csv','w',newline='') as fp:
    writer = csv.writer(fp)
    writer.writerow(headers)
    writer.writerows(values)

也可以使用字典的方式把数据写入进去。这时候就需要使用DictWriter了:

import csv

headers = ['name','age','classroom']
values = [
    {"name":'wenn',"age":20,"classroom":'222'},
    {"name":'abc',"age":30,"classroom":'333'}
]
with open('test.csv','w',newline='') as fp:
    writer = csv.DictWriter(fp,headers)
    writer = csv.writeheader()
    writer.writerow({'name':'zhiliao',"age":18,"classroom":'111'})
    writer.writerows(values)

你可能感兴趣的:(爬虫)