>  기사  >  백엔드 개발  >  xpath, JsonPath 및 bs4에 Python을 사용하는 방법은 무엇입니까?

xpath, JsonPath 및 bs4에 Python을 사용하는 방법은 무엇입니까?

WBOY
WBOY앞으로
2023-05-09 21:04:061536검색

1. douban.com/simple

    Import lxml.etreefrom lxml import etree
  • etree.parse() 로컬 파일 구문 분석html_tree = etree. 구문 분석(' XX.html')
  • pip install lxml ‐i https://pypi.douban.com/simple

  • 导入lxml.etreefrom lxml import etree

  • etree.parse() 解析本地文件html_tree = etree.parse('XX.html')

  • etree.HTML() 服务器响应文件html_tree = etree.HTML(response.read().decode('utf‐8')

    etree.HTML() 서버 응답 파일 html_tree = etree.HTML(response.read().decode('utf‐8')
  • .html_tree.xpath (xpath 경로)

1.2 xpath의 기본 구문

1. 경로 쿼리
  • 계층 관계에 관계없이 모든 하위 노드 찾기
  • 직접 하위 노드 찾기

2. 술어 쿼리

//div[@id] 
//div[@id="maincontent"]

3. 속성 쿼리

//@class

4. 퍼지 쿼리

//div[contains(@id, "he")] 
//div[starts‐with(@id, "he")]

5. 논리 연산

//div/h2/text()

1.3 예시

xpath.html rreee

//div[@id="head" and @class="s_down"] 
//title | //price

1.4

Climb Baidu 검색 버튼 값 가져오기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    <ul>
        <li id="l1" class="class1">北京</li>
        <li id="l2" class="class2">上海</li>
        <li id="d1">广州</li>
        <li>深圳</li>
    </ul>
</body>
</html>

xpath, JsonPath 및 bs4에 Python을 사용하는 방법은 무엇입니까?

1.5 웹마스터 자료 사진 크롤링

from lxml import etree

# xpath解析
# 本地文件:                                          etree.parse
# 服务器相应的数据    response.read().decode(&#39;utf-8&#39;)  etree.HTML()


tree = etree.parse(&#39;xpath.html&#39;)

# 查找url下边的li
li_list = tree.xpath(&#39;//body/ul/li&#39;)
print(len(li_list))  # 4

# 获取标签中的内容
li_list = tree.xpath(&#39;//body/ul/li/text()&#39;)
print(li_list)  # [&#39;北京&#39;, &#39;上海&#39;, &#39;广州&#39;, &#39;深圳&#39;]

# 获取带id属性的li
li_list = tree.xpath(&#39;//ul/li[@id]&#39;)
print(len(li_list))  # 3

# 获取id为l1的标签内容
li_list = tree.xpath(&#39;//ul/li[@id="l1"]/text()&#39;)
print(li_list)  # [&#39;北京&#39;]

# 获取id为l1的class属性值
c1 = tree.xpath(&#39;//ul/li[@id="l1"]/@class&#39;)
print(c1)  # [&#39;class1&#39;]

# 获取id中包含l的标签
li_list = tree.xpath(&#39;//ul/li[contains(@id, "l")]/text()&#39;)
print(li_list)  # [&#39;北京&#39;, &#39;上海&#39;]
# 获取id以d开头的标签
li_list = tree.xpath(&#39;//ul/li[starts-with(@id,"d")]/text()&#39;)
print(li_list)  # [&#39;广州&#39;]
# 获取id为l2并且class为class2的标签
li_list = tree.xpath(&#39;//ul/li[@id="l2" and @class="class2"]/text()&#39;)
print(li_list)  # [&#39;上海&#39;]
# 获取id为l2或id为d1的标签
li_list = tree.xpath(&#39;//ul/li[@id="l2"]/text() | //ul/li[@id="d1"]/text()&#39;)
print(li_list)  # [&#39;上海&#39;, &#39;广州&#39;]

2. JsonPath

2.1 pip 설치

import urllib.request
from lxml import etree
url = &#39;http://www.baidu.com&#39;
headers = {
    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36&#39;
}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode(&#39;utf-8&#39;)
tree = etree.HTML(content)
value = tree.xpath(&#39;//input[@id="su"]/@value&#39;)
print(value)

2.2 jsonpath

# 需求 下载的前十页的图片
# https://sc.chinaz.com/tupian/qinglvtupian.html   1
# https://sc.chinaz.com/tupian/qinglvtupian_page.html
import urllib.request
from lxml import etree
def create_request(page):
    if (page == 1):
        url = &#39;https://sc.chinaz.com/tupian/qinglvtupian.html&#39;
    else:
        url = &#39;https://sc.chinaz.com/tupian/qinglvtupian_&#39; + str(page) + &#39;.html&#39;
    headers = {
        &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36&#39;,
    }
    request = urllib.request.Request(url=url, headers=headers)
    return request
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode(&#39;utf-8&#39;)
    return content
def down_load(content):
    #     下载图片
    # urllib.request.urlretrieve(&#39;图片地址&#39;,&#39;文件的名字&#39;)
    tree = etree.HTML(content)
    name_list = tree.xpath(&#39;//div[@id="container"]//a/img/@alt&#39;)
    # 一般设计图片的网站都会进行懒加载
    src_list = tree.xpath(&#39;//div[@id="container"]//a/img/@src2&#39;)
    print(src_list)
    for i in range(len(name_list)):
        name = name_list[i]
        src = src_list[i]
        url = &#39;https:&#39; + src
        urllib.request.urlretrieve(url=url, filename=&#39;./loveImg/&#39; + name + &#39;.jpg&#39;)
if __name__ == &#39;__main__&#39;:
    start_page = int(input(&#39;请输入起始页码&#39;))
    end_page = int(input(&#39;请输入结束页码&#39;))

    for page in range(start_page, end_page + 1):
        # (1) 请求对象的定制
        request = create_request(page)
        # (2)获取网页的源码
        content = get_content(request)
        # (3)下载
        down_load(content)

J 사용 SONPath 구문 요소 및 해당 XPath 요소 비교:

xpath, JsonPath 및 bs4에 Python을 사용하는 방법은 무엇입니까?

예:

jsonpath.json

pip install jsonpath
obj = json.load(open(&#39;json文件&#39;, &#39;r&#39;, encoding=&#39;utf‐8&#39;)) 
ret = jsonpath.jsonpath(obj, &#39;jsonpath语法&#39;)

3. BeautifulSoup

3.1 기본 소개

1. bs4 설치

2 가져오기

from bs4 import BeautifulSoup

3. 객체 생성

서버 응답 파일 생성 객체 수프 = BeautifulSoup(response.read().decode(), 'lxml')

  • 로컬 파일 생성 객체 수프 = BeautifulSoup (open('1.html'), 'lxml')

  • 참고:
파일 열기의 기본 인코딩 형식은 gbk이므로 열기 인코딩 형식을 utf-8

3.2로 지정해야 합니다. 설치 및 생성

{ "store": {
    "book": [
      { "category": "修真",
        "author": "六道",
        "title": "坏蛋是怎样练成的",
        "price": 8.95
      },
      { "category": "修真",
        "author": "天蚕土豆",
        "title": "斗破苍穹",
        "price": 12.99
      },
      { "category": "修真",
        "author": "唐家三少",
        "title": "斗罗大陆",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "修真",
        "author": "南派三叔",
        "title": "星辰变",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "author": "老马",
      "color": "黑色",
      "price": 19.95
    }
  }
}

3.3 노드 위치 지정
import json
import jsonpath

obj = json.load(open(&#39;jsonpath.json&#39;, &#39;r&#39;, encoding=&#39;utf-8&#39;))

# 书店所有书的作者
author_list = jsonpath.jsonpath(obj, &#39;$.store.book[*].author&#39;)
print(author_list)  # [&#39;六道&#39;, &#39;天蚕土豆&#39;, &#39;唐家三少&#39;, &#39;南派三叔&#39;]

# 所有的作者
author_list = jsonpath.jsonpath(obj, &#39;$..author&#39;)
print(author_list)  # [&#39;六道&#39;, &#39;天蚕土豆&#39;, &#39;唐家三少&#39;, &#39;南派三叔&#39;, &#39;老马&#39;]

# store下面的所有的元素
tag_list = jsonpath.jsonpath(obj, &#39;$.store.*&#39;)
print(
    tag_list)  # [[{&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;六道&#39;, &#39;title&#39;: &#39;坏蛋是怎样练成的&#39;, &#39;price&#39;: 8.95}, {&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;天蚕土豆&#39;, &#39;title&#39;: &#39;斗破苍穹&#39;, &#39;price&#39;: 12.99}, {&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;唐家三少&#39;, &#39;title&#39;: &#39;斗罗大陆&#39;, &#39;isbn&#39;: &#39;0-553-21311-3&#39;, &#39;price&#39;: 8.99}, {&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;南派三叔&#39;, &#39;title&#39;: &#39;星辰变&#39;, &#39;isbn&#39;: &#39;0-395-19395-8&#39;, &#39;price&#39;: 22.99}], {&#39;author&#39;: &#39;老马&#39;, &#39;color&#39;: &#39;黑色&#39;, &#39;price&#39;: 19.95}]

# store里面所有东西的price
price_list = jsonpath.jsonpath(obj, &#39;$.store..price&#39;)
print(price_list)  # [8.95, 12.99, 8.99, 22.99, 19.95]

# 第三个书
book = jsonpath.jsonpath(obj, &#39;$..book[2]&#39;)
print(book)  # [{&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;唐家三少&#39;, &#39;title&#39;: &#39;斗罗大陆&#39;, &#39;isbn&#39;: &#39;0-553-21311-3&#39;, &#39;price&#39;: 8.99}]

# 最后一本书
book = jsonpath.jsonpath(obj, &#39;$..book[(@.length-1)]&#39;)
print(book)  # [{&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;南派三叔&#39;, &#39;title&#39;: &#39;星辰变&#39;, &#39;isbn&#39;: &#39;0-395-19395-8&#39;, &#39;price&#39;: 22.99}]
# 	前面的两本书
book_list = jsonpath.jsonpath(obj, &#39;$..book[0,1]&#39;)
# book_list = jsonpath.jsonpath(obj,&#39;$..book[:2]&#39;)
print(
    book_list)  # [{&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;六道&#39;, &#39;title&#39;: &#39;坏蛋是怎样练成的&#39;, &#39;price&#39;: 8.95}, {&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;天蚕土豆&#39;, &#39;title&#39;: &#39;斗破苍穹&#39;, &#39;price&#39;: 12.99}]

# 条件过滤需要在()的前面添加一个?
# 	 过滤出所有的包含isbn的书。
book_list = jsonpath.jsonpath(obj, &#39;$..book[?(@.isbn)]&#39;)
print(
    book_list)  # [{&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;唐家三少&#39;, &#39;title&#39;: &#39;斗罗大陆&#39;, &#39;isbn&#39;: &#39;0-553-21311-3&#39;, &#39;price&#39;: 8.99}, {&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;南派三叔&#39;, &#39;title&#39;: &#39;星辰变&#39;, &#39;isbn&#39;: &#39;0-395-19395-8&#39;, &#39;price&#39;: 22.99}]
# 哪本书超过了10块钱
book_list = jsonpath.jsonpath(obj, &#39;$..book[?(@.price>10)]&#39;)
print(
    book_list)  # [{&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;天蚕土豆&#39;, &#39;title&#39;: &#39;斗破苍穹&#39;, &#39;price&#39;: 12.99}, {&#39;category&#39;: &#39;修真&#39;, &#39;author&#39;: &#39;南派三叔&#39;, &#39;title&#39;: &#39;星辰变&#39;, &#39;isbn&#39;: &#39;0-395-19395-8&#39;, &#39;price&#39;: 22.99}]

3.5 노드 정보

1.根据标签名查找节点 
	soup.a 【注】只能找到第一个a 
		soup.a.name 
		soup.a.attrs 
2.函数 
	(1).find(返回一个对象) 
		find(&#39;a&#39;):只找到第一个a标签
		find(&#39;a&#39;, title=&#39;名字&#39;) 
		find(&#39;a&#39;, class_=&#39;名字&#39;) 
	(2).find_all(返回一个列表) 
		find_all(&#39;a&#39;) 查找到所有的a 
		find_all([&#39;a&#39;, &#39;span&#39;]) 返回所有的a和span 
		find_all(&#39;a&#39;, limit=2) 只找前两个a 
	(3).select(根据选择器得到节点对象)【推荐】 
		1.element 
			eg:p 
		2..class 
			eg:.firstname 
		3.#id
			eg:#firstname 
		4.属性选择器 
			[attribute] 
				eg:li = soup.select(&#39;li[class]&#39;) 
			[attribute=value] 
				eg:li = soup.select(&#39;li[class="hengheng1"]&#39;) 
		5.层级选择器 
			element element 
				div p 
			element>element 
				div>p 
			element,element 
				div,p 
					eg:soup = soup.select(&#39;a,span&#39;)
1.根据标签名查找节点 
	soup.a 【注】只能找到第一个a 
		soup.a.name 
		soup.a.attrs 
2.函数 
	(1).find(返回一个对象) 
		find(&#39;a&#39;):只找到第一个a标签
		find(&#39;a&#39;, title=&#39;名字&#39;) 
		find(&#39;a&#39;, class_=&#39;名字&#39;) 
	(2).find_all(返回一个列表) 
		find_all(&#39;a&#39;) 查找到所有的a 
		find_all([&#39;a&#39;, &#39;span&#39;]) 返回所有的a和span 
		find_all(&#39;a&#39;, limit=2) 只找前两个a 
	(3).select(根据选择器得到节点对象)【推荐】 
		1.element 
			eg:p 
		2..class 
			eg:.firstname 
		3.#id
			eg:#firstname 
		4.属性选择器 
			[attribute] 
				eg:li = soup.select(&#39;li[class]&#39;) 
			[attribute=value] 
				eg:li = soup.select(&#39;li[class="hengheng1"]&#39;) 
		5.层级选择器 
			element element 
				div p 
			element>element 
				div>p 
			element,element 
				div,p 
					eg:soup = soup.select(&#39;a,span&#39;)

3.6 사용 예

bs4.html

(1).获取节点内容:适用于标签中嵌套标签的结构 
	obj.string 
	obj.get_text()【推荐】 
(2).节点的属性 
	tag.name 获取标签名 
		eg:tag = find(&#39;li) 
			print(tag.name) 
	tag.attrs将属性值作为一个字典返回 
(3).获取节点属性 
	obj.attrs.get(&#39;title&#39;)【常用】 
	obj.get(&#39;title&#39;) 
	obj[&#39;title&#39;]
(1).获取节点内容:适用于标签中嵌套标签的结构 
	obj.string 
	obj.get_text()【推荐】 
(2).节点的属性 
	tag.name 获取标签名 
		eg:tag = find(&#39;li) 
			print(tag.name) 
	tag.attrs将属性值作为一个字典返回 
(3).获取节点属性 
	obj.attrs.get(&#39;title&#39;)【常用】 
	obj.get(&#39;title&#39;) 
	obj[&#39;title&#39;]

3.7 스타벅스 제품명 파싱

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div>
        <ul>
            <li id="l1">张三</li>
            <li id="l2">李四</li>
            <li>王五</li>
            <a href="" id=" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" " class="a1">google</a>
            <span>嘿嘿嘿</span>
        </ul>
    </div>


    <a href="" title=" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" a2">百度</a>

    <div id="d1">
        <span>
            哈哈哈
        </span>
    </div>

    <p id="p1" class="p1">呵呵呵</p>
</body>
</html>

위 내용은 xpath, JsonPath 및 bs4에 Python을 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제