爬虫案例(读书网)

一.我们还是使用简单的bs4库和lxml,使用xpath:

导入下面的库:

python 复制代码
import requests
from bs4 import BeautifulSoup
from lxml import etree

我们可以看见它的div和每个书的div框架,这样会观察会快速提高我们的简单爬取能力。

二.实例代码:

python 复制代码
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'}
link="https://www.dushu.com/"
r=requests.get(link,headers=headers)
r.encoding='utf-8'

soup=BeautifulSoup(r.text,'lxml')
house_list=soup.find_all('div',class_="border books-center")
html=etree.HTML(r.text)
    # name=html.xpath('//div[@class="property-content-title"]/h3/text()')
# for house in house_list:
#     name=soup.find('div',class_="nlist").a.strong.text()
#
#     print(name)
name=html.xpath('//div[@class="bookname"]/a/text()')
# href=html.xpath('//div[@class="nlist"]/div/ul/li/a/@href')

print(name)
for i in name:
    print(i)

运行结果如下:

我们成功抓取了网页上书籍的名字,我们可以把它放入一个文件或者文本里面。

三.总结

我们简单的抓取书籍,先找到它需要的大div或者是ur、然后在里面找到自己需要抓取的数据,我们开始练习这样简单案例,会提高爬虫的理解。下次我会加上数据库和可视化

相关推荐
Kratzdisteln3 分钟前
【MVCD】PPT提纲汇总
经验分享·python
一个无名的炼丹师32 分钟前
GraphRAG深度解析:从原理到实战,重塑RAG检索增强生成的未来
人工智能·python·rag
用户8356290780511 小时前
用Python轻松管理Word页脚:批量处理与多节文档技巧
后端·python
进击的松鼠1 小时前
LangChain 实战 | 快速搭建 Python 开发环境
python·langchain·llm
小北方城市网1 小时前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)
大数据·网络·数据结构·python·架构·数据库架构
我的offer在哪里2 小时前
Hugging Face:让大模型触手可及的魔法工厂
人工智能·python·语言模型·开源·ai编程
汤姆yu2 小时前
基于python大数据的协同过滤音乐推荐系统
大数据·开发语言·python
爱学习的小道长2 小时前
Python Emoji库的使用教程
开发语言·python
Data_agent2 小时前
Cssbuy 模式淘宝 / 1688 代购系统南美市场搭建指南
大数据·python