python爬虫学习随记

本文介绍了一个基于Python的豆瓣网页爬虫实例,利用requests和BeautifulSoup库抓取网页数据,包括短评内容及评分等信息,并演示了如何使用find_all方法进行数据解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过豆瓣网页源代码,了解python爬虫的一些基础知识;mocc网的一个例子

么有html经验的我,真是困难啊,这里边做边学html基础知识 http://www.runoob.com/tags/html-reference.html

主要有2个库:

requests: http://www.python-requests.org/en/master/

bs4: https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

import requests
from bs4 import BeautifulSoup
import re
sum = 0
r = requests.get('https://book.douban.com/subject/26853356/comments/') #豆瓣小说 鱼王 短评界面
soup = BeautifulSoup(r.text, 'lxml')
pattern = soup.find_all('p', 'comment-content') #  看下面find_all的用法
for item in pattern:
    print(item.string)
pattern_s = re.compile('<span class="user-stars allstar(.*?) rating"')#网页中评价分数匹配
p = re.findall(pattern_s, r.text)  #返回列表
for star in p:
    sum += int(star)
print("the average value is: {:.2f}".format(sum/len(p)))

一个经典的例子记录bs4中find_all的用法:

详见:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#find-all

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

find_all( name , attrs , recursive , text , **kwargs )

find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件.

soup.find_all("title")   #tag名称
# [<title>The Dormouse's story</title>]

soup.find_all("p", "title")  #css类名搜索
# [<p class="title"><b>The Dormouse's story</b></p>]

soup.find_all("a")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find_all(id="link2")# 按属性 值搜索
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

import re
soup.find(text=re.compile("sisters"))
# u'Once upon a time there were three little sisters; and their names were\n'

正则表达式用法


re.compile 函数

compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。

语法格式为:

re.compile(pattern[, flags])

findall 

在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

findall(string[, pos[, endpos]])



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值