python爬虫解析器bs4,xpath,pquery

0x00 bs4

解析器的作用就是可以直接解析html页面,可以直接从网页中提取标签中的内容,而不用在使用正则表达式进行提起数据

bash 复制代码
import requests
from bs4 import BeautifulSoup
html_content = '''
<li id='123'><a href='dfsdf'>123</a>789</li>
<li id='55'><a href='f'>456</a>888</li>
'''
# 解析HTML
soup = BeautifulSoup(html_content, 'html.parser')  
li=soup.find_all('li')  #查找所用的li标签
print(li[0].text)       #把第一个li标签中内容读取出来
a=li[0].find("a")       #在第一个li标签中查找a标签
print(a.text)           
print(a.get("href"))   #在读取a标签href的属性值



li=soup.find('li',{"id":"123"})  #查找id为123的li标签
for i in li:
    print(i.text)


案列爬取图片

https://haowallpaper.com/

bash 复制代码
import requests
from bs4 import BeautifulSoup
url='https://haowallpaper.com/'
html_content=requests.get(url).text
html=BeautifulSoup(html_content,"html.parser")
div=html.find_all("div",{"class":"card"})
n=1
for a_list in div:
    src=a_list.find("img")
    src=src.get("src")
    rep=requests.get(src)
    with open(f"{n}.jpg",'wb+') as f:
        f.write(rep.content)   #要用content而不是text文本
        n+=1

0x01 xpath

案列爬取什么值得买手机价格和手机型号,当源码过多时可以把源码下载下来,删除无用代码然后在进行分析

bash 复制代码
import requests
from lxml import etree
from PIL import Image, ImageDraw, ImageFont
headers={"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"}
url='https://www.smzdm.com/fenlei/zhinengshouji/'
req=requests.get(url)
html=etree.HTML(req.content)
price_list=html.xpath('//a[@class="z-highlight "]/text()')
title_list=html.xpath('//h5[@class="feed-block-title"]/a[1]/text()')
# a_list=html.xpath("//div[@class='z-feed-img']//img/@src")
count=0
for i in price_list:
   count+=1
with open("3.txt","a+",encoding='gbk') as f:
    for i in range(0,count):
        f.write(price_list[i].strip())
        f.write(title_list[i].strip()+'\n')

0x02 PyQuery

1.PyQuery基础使用

bash 复制代码
from pyquery import   PyQuery
html='''
<div class='aaa'><a href='www.123.com'>aaa</a>aaa1</div>
<div class='bbb'><a href='www.456.com'>bbb</a>bbb1</div>
<div class='ccc' id='cc'><a href='www.789.com'>ccc</a>ccc1</div>
'''
p=PyQuery(html)
#a=p("div a")和a=p("div")("a")是一样的
div1=p("div") #选取所有的div标签
div=p("div .aaa") #选取div的class属性值为aaa的div标签
div2=p("div #cc") #选取div的id值为cc的div标签
print("-------")
print(div)
print("-------")
print(div2)
print("-------")
a=p("div a").attr("href") #提取div标签下的a标签的href属性值,只会提取一个href值
print(a)
a1=p("div a").items()#一个包含所有a标签的迭代器,有很多内容时可以这样提取
for a2 in a1:
    href=a2.attr("href")
    text=a2.text() #获取a标签中的文本
    print(href)
    print(text)

修改html页面代码

bash 复制代码
from pyquery import   PyQuery
html='''
<div class='aaa'><a href='www.123.com'>aaa</a>aaa1</div>
<div class='bbb'><a href='www.456.com'>bbb</a>bbb1</div>
<div class='ccc' id='cc'><a href='www.789.com'>ccc</a>ccc1</div>
'''
p=PyQuery(html)
p("div .aaa").after("<div>qqq</div>") #在第一个div后加一个div标签
p("div .aaa").append("<div>aaa</div>") #在第一个div里面加一个div标签
p("div .aaa").attr("id","111")#在第一个div加一个属性id为111
p("div .aaa").remove()#删除第一个div
p("div .aaa").remove_attr("id")#删除第一个div的id

2.案列豆瓣读书爬取短评,书评,评分,书名,内容,作者简介

注意这里热门短评是会刷新的,只读取5条,每次读取的都有不一样的地方

bash 复制代码
import requests
from pyquery import PyQuery
headers={"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"}
url='https://book.douban.com/subject/4913064/'
rep=requests.get(url,headers=headers)
p=PyQuery(rep.text)
with open("1.txt",'a+',encoding='utf-8') as f:
    title=p("title").text()
    score=p("div #interest_sectl div div strong").text()
    f.write(f"书名:{title}\n评分{score}\n")
    content=p("div .intro").eq(0)("p").text() #选择第一个class为intro的div下所有的p标签
    composer=p("div .intro").eq(1)("p").text()#选择第二个class为intro的div下所有的p标签
    f.write(f"内容简介:{content}\n作者简介:{composer}")
    comments=p("li p span ").items()
    f.write("\n短评:\n")
    for i in comments:
        comment=i.text()
        f.write(f"{comment}\n")
    shupin_1=p("div.main-bd ").items()
    f.write("书评:\n")
    for j in shupin_1:
        shupin_2=j("h2 a").text()
        shupin_3=j("div div .short-content").text().replace("这篇书评可能有关键情节透露","").replace("...  (展开)","")
        f.write(f"{shupin_2+shupin_3}\n")
相关推荐
曲幽6 分钟前
FastAPI不止于API:手把手教你用Jinja2打造动态Web页面
python·fastapi·backend·jinja2·full stack·template engine·web development
禹凕11 分钟前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
Ulyanov15 分钟前
基于Pymunk物理引擎的2D坦克对战游戏开发
python·游戏·pygame·pymunk
铉铉这波能秀15 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马24 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
IOsetting25 分钟前
金山云主机添加开机路由
运维·服务器·开发语言·网络·php
程序媛徐师姐31 分钟前
Python基于爬虫的网络小说数据分析系统【附源码、文档说明】
爬虫·python·python爬虫·网络小说数据分析系统·pytho网络小说数据分析系统·python爬虫网络小说·python爬虫的网络小说数据
清水白石00838 分钟前
深入解析 LRU 缓存:从 `@lru_cache` 到手动实现的完整指南
java·python·spring·缓存
林开落L39 分钟前
从零开始学习Protobuf(C++实战版)
开发语言·c++·学习·protobuffer·结构化数据序列化机制
JaydenAI42 分钟前
[LangChain之链]LangChain的Chain——由Runnable构建的管道
python·langchain