爬虫案例(读书网)

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

相关推荐
再努力"亿"点点4 分钟前
爬取m3u8视频完整教程
开发语言·python
悟能不能悟21 分钟前
if __name__=‘__main__‘的用处
python
Source.Liu32 分钟前
【Python基础】 15 Rust 与 Python 基本类型对比笔记
笔记·python·rust
前端世界32 分钟前
Python 正则表达式实战:用 Match 对象轻松解析拼接数据流
python·正则表达式·php
Blurpath34 分钟前
如何利用静态代理IP优化爬虫策略?从基础到实战的完整指南
爬虫·网络协议·ip代理·住宅代理
DreamNotOver1 小时前
基于Scikit-learn集成学习模型的情感分析研究与实现
python·scikit-learn·集成学习
Learn Beyond Limits1 小时前
Error metrics for skewed datasets|倾斜数据集的误差指标
大数据·人工智能·python·深度学习·机器学习·ai·吴恩达
半瓶榴莲奶^_^2 小时前
python基础案例-数据可视化
python·信息可视化·数据分析
wjayg2252 小时前
网络爬虫是自动从互联网上采集数据的程序
爬虫
mit6.8242 小时前
[网络入侵AI检测] docs | 任务二分类与多分类
python