python爬取豆瓣读书,python爬取数据豆瓣读书

xpath爬取脚本:

from urllib import request

from lxml import etree

base_url=“https://tieba.baidu.com/f?kw=nba”

response=request.urlopen(base_url)

html=response.read().decode(‘utf-8’)

htmls=etree.HTML(html)

titles=htmls.xpath(’//div[@class=“threadlist_lz clearfix”]/div/a/@title’)

一开始在父级div没找到,因此再上一级找爷爷辈div,然后加个/div回到父级

//表示在整个html文档寻找,@表示寻找类名,再加一个/div表示它的下一级

print(titles)发现输出的是一个列表

for i in titles:

print(i)

为啥不直接找呢?

因为没有class标签,所以不好找,所以找它的父亲,看套再哪个class里

//div[@class=“pl2”]/a/@title

//p[@class=“pl”]/text()作者

P标签下用text找

//span[@class=“rating_nums”]/text()评分

短评

//span[@class=“inq”]/text()

//div[@class=“movie-content”]/a/img/@src

图片

#爬取豆瓣读书top250

建立一个文件io对象

fp=open(’./douban.txt’,‘a’,encoding=‘utf-8’)

采集源码

def index():

for i in range(0,226,25):#制作页码

# print(i)

base_url=‘https://book.douban.com/top250?start={0}’.format(i)

# print(base_url)

#抓取源码阶段

response=request.urlopen(base_url)

html=response.read().decode(‘utf-8’)

#处理源码(用etree将html转换为xml

htmls=etree.HTML(html)#就可以用xpath语言写了

clean_sto(htmls)

清洗数据并保存

def clean_sto(htmls):

titles=htmls.xpath(’//div[@class=“pl2”]/a/@title’)

# print(titles)发现是一个一个的列表

for i in titles:

# print(i)

fp.write(i+’\n’)

if name==‘main’:

index()

fp.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值