爬虫案例(读书网)

一.我们还是使用简单的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、然后在里面找到自己需要抓取的数据,我们开始练习这样简单案例,会提高爬虫的理解。下次我会加上数据库和可视化

相关推荐
BD_Marathon2 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw2 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn3 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern095 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980116 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
databook8 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer9 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
2601_9679801112 小时前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者12 小时前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc
承渊政道13 小时前
【Python编程快速上手—让繁琐工作自动化】(模式匹配与正则表达式:从找到一个号码到批量提取信息)
python·正则表达式·pycharm·自动化·模式匹配