Python爬虫工具BeautifulSoup使用详解

一、模块简介

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找、修改文档的方式。Beautiful Soup会帮你节省工作时间。

二、方法利用

1、安装beautifulsoup

pip install beautifulsoup4

2、引入模块

from bs4 import  BeautifulSoup

3、选择解析器解析指定内容

soup=beautifulsoup(解析内容,解析器)

常用解析器:html.parser,lxml,xml,html5lib
有时候需要安装安装解析器:比如 pip3 install lxml
BeautifulSoup默认支持Python的标准HTML解析库,但是它也支持一些第三方的解析库:

解析器使用方法优势劣势
Python标准库BeautifulSoup(markup,“html.parser”)Python的内置标准库、执行速度适中、文档容错能力强Python 2.7.3 or 3.2.2之前的版本中文档容错能力差
lxml HTML解析器BeautifulSoup(markup, “lxml”)速度快、文档容错能力强需要安装C语言库
lxml XML解析器BeautifulSoup(markup, [“lxml - xml”])、BeautifulSoup(markup, “xml”)速度快、唯一支持XML的解析器需要安装C语言库
html5libBeautifulSoup(markup, “html5lib”)最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档速度慢、不依赖外部扩展

几个简单的浏览结构化数据的方法

#获取Tag,通俗点就是HTML中的一个个标签
soup.title                    # 获取整个title标签字段:<title>The Dormouse's story</title>
soup.title.name               # 获取title标签名称  :title
soup.title.parent.name        # 获取 title 的父级标签名称:head
soup.p                        # 获取第一个p标签字段:<p class="title"><b>The Dormouse's story</b></p>
soup.p['class']               # 获取第一个p中class属性值:title
soup.p.get('class')           # 等价于上面
soup.a                        # 获取第一个a标签字段
soup.find_all('a')            # 获取所有a标签字段
soup.find(id="link3")         # 获取属性id值为link3的字段
soup.a['class'] = "newClass"  # 可以对这些属性和内容等等进行修改
del bs.a['class']             # 还可以对这个属性进行删除
soup.find('a').get('id')      # 获取class值为story的a标签中id属性的值
soup.title.string             # 获取title标签的值  :The Dormouse's story

三、具体利用

1、获取拥有指定属性的标签

方法一:获取单个属性
soup.find_all('div',id="even")            # 获取所有id=even属性的div标签
soup.find_all('div',attrs={'id':"even"})    # 效果同上

方法二:
soup.find_all('div',id="even",class_="square")            # 获取所有id=even并且class=square属性的div标签
soup.find_all('div',attrs={"id":"even","class":"square"})    # 效果同上

2、获取标签的属性值

方法一:通过下标方式提取
for link in soup.find_all('a'):
    print(link['href'])        //等同于 print(link.get('href'))

方法二:利用attrs参数提取
for link in soup.find_all('a'):
    print(link.attrs['href'])

3、获取标签中的内容

divs = soup.find_all('div')        # 获取所有的div标签
for div in divs:                   # 循环遍历div中的每一个div
    a = div.find_all('a')[0]      # 查找div标签中的第一个a标签     
    print(a.string)              # 输出a标签中的内容

如果结果没有正确显示,可以转换为list列表

4、stripped_strings

去除\n换行符等其他内容 stripped_strings

divs = soup.find_all('div')
for div in divs:
    infos = list(div.stripped_strings)        # 去掉空格换行等
    bring(infos)

四、输出

1、格式化输出prettify()

prettify() 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行

markup = '<a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
soup.prettify()
# '<html>\n <head>\n </head>\n <body>\n  <a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >\n...'
print(soup.prettify())
# <html>
#  <head>
#  </head>
#  <body>
#   <a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
#    I linked to
#    <i>
#     example.com
#    </i>
#   </a>
#  </body>
# </html>

2、get_text()

如果只想得到tag中包含的文本内容,那么可以调用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:

markup = '<a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup)
soup.get_text()
'\nI linked to example.com\n'
soup.i.get_text()
'example.com'

### 构建任务失败解决方案 当遇到 `Execution failed for task ':app:shrinkReleaseRes'` 错误时,这通常意味着资源压缩过程中出现了问题。此错误可能由多种原因引起,包括但不限于配置不正确、依赖冲突或特定于项目的其他因素。 #### 可能的原因分析 1. **ProGuard 或 R8 配置不当** ProGuard 和 R8 是用于优化和混淆代码以及减少 APK 大小的工具。如果这些工具的配置存在问题,可能会导致资源无法正常处理[^1]。 2. **重复资源** 如果项目中有多个模块定义了相同的资源名称,可能导致冲突并引发该错误。检查是否存在重名的 drawable、string 等资源文件[^2]。 3. **第三方库兼容性** 某些第三方库可能与当前使用的 Gradle 插件版本或其他库存在兼容性问题,从而影响到资源打包过程中的行为[^3]。 4. **Gradle 缓存问题** 有时旧缓存数据会干扰新编译的结果,尝试清理本地仓库和重新同步项目可以帮助排除此类潜在障碍[^4]。 #### 推荐的操作方法 为了有效解决问题,建议按照以下步骤逐一排查: ```bash # 清理项目构建目录 ./gradlew clean # 删除 .gradle 文件夹下的所有内容以清除缓存 rm -rf ~/.gradle/caches/ ``` 调整 `build.gradle` 中的相关设置也是一个重要环节: ```groovy android { ... buildTypes { release { minifyEnabled true // 是否启用代码缩减 shrinkResources true // 是否开启资源压缩 proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' // 尝试禁用 shrinkResources 来测试是否为资源压缩引起的错误 // shrinkResources false } } } ``` 此外,在 `proguard-rules.pro` 文件内添加必要的保留规则,防止关键类被意外移除: ```text -keep class com.example.yourpackage.** { *; } # 替换为你自己的包路径 -dontwarn androidx.**,com.google.** # 忽略警告信息 ``` 最后,确保所使用的 Android Studio 版本是最新的稳定版,并且已经应用了所有的补丁更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值