Python爬虫案例1——豆瓣出版社爬取并写入文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43862765/article/details/100979520

①先看一下效果吧:

②具体的操作代码如下:

#爬取豆瓣出版社信息
import urllib.request
import re

data = urllib.request.urlopen("https://read.douban.com/provider/all").read().decode("utf-8")
patten = '<div class="name">(.*?)</div>'
result = re.compile(patten).findall(data)
print(result)
print(len(result))

file = open("C:/Users/HP/Desktop/1.txt","w",encoding='utf-8')
for i in range(0,len(result)):
    file.write(result[i] + '\n')
print('写入成功!')
file.close()

其中,有几个点我说一下:

1)urllib是Python爬虫时必须要用的一个内置库

2)re是正则表达式要用的库;

3)decoding("utf-8")和后面的encoding都是为了兼容大多数编译器等等,要不然编码出现问题会出bug

4)patten里面的标签是在网址下按下“F12”,选择对应的模块进行查看的,正则表达式的一些用法,我过段时间会写的

5)Python的打开、写入、创建文件等等大家肯定都会了

运行在idle上的显示信息是:

一共96个出版社,不相信?可以手动数数。

猜你喜欢

转载自blog.csdn.net/weixin_43862765/article/details/100979520
今日推荐