人工智能 -- python3 爬虫:BeautifulSoup标签查找与信息提取

人工智能 – python3 爬虫:BeautifulSoup标签查找与信息提取

前言

因新旧版本问题,BeautifulSoup所存放的包有变化,要用新方式import bs4.BeautifulSoup导入,习惯上:from bs4 import BeautifulSoup as bs
小技巧:若有类似情况,可以在pycharm编辑器中打出函数,“ctrl”+单击,便可出现提示info,如下:
在这里插入图片描述

BeautifulSoup的使用

以下面代码为例:

from urllib import request
from bs4 import BeautifulSoup as bs

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}
url = "https://..." # 自定义
resp = request.Request(url, headers=headers)
html_data = request.urlopen(resp).read().decode('utf-8', 'ignore') 
soup = bs(html_data, 'html.parser')

接下来便可以用soup对象来搞事情了:

1. 查找a标签

(1)查找所有a标签

for x in soup.find_all('a'):
    print(x)

运行结果:

<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>

(2)查找所有a标签,且属性值href中需要保护关键字“”

for x in soup.find_all('a',href = re.compile('lacie')):
    print(x)

运行结果:

<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>

(3)查找所有a标签,且字符串内容包含关键字“Elsie”

for x in soup.find_all('a',string = re.compile('Elsie')):
    print(x)

运行结果:

<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

(4)查找body标签的所有子标签,并循环打印输出

for x in soup.find('body').children:
    if isinstance(x,bs4.element.Tag):        #使用isinstance过滤掉空行内容
        print(x)

运行结果:

<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 class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
2. 信息提取(链接提取)

(1)解析信息标签结构,查找所有a标签,并提取每个a标签中href属性的值(即链接),然后存在空列表

linklist = []
for x in soup.find_all('a'):
    link = x.get('href')
    if link:
        linklist.append(link)
       
for x in linklist:        #验证:环打印出linklist列表中的链接
    print(x)

运行结果:

http://example.com/elsie
http://example.com/lacie
http://example.com/tillie

小结:链接提取 <—> 属性内容提取 <—> x.get(‘href’)

(2)解析信息标签结构,查找所有a标签,且每个a标签中href中包含关键字“elsie”,然后存入空列表中;

linklst = []
for x in soup.find_all('a', href = re.compile('elsie')):
    link = x.get('href')
    if link:
        linklst.append(link)
    
for x in linklst:        #验证:循环打印出linklist列表中的链接
    print(x)

运行结果:

http://example.com/elsie

小结:在进行a标签查找时,加入了对属性值href内容的正则匹配内容 <—> href = re.compile(‘elsie’)

(3)解析信息标签结构,查询所有a标签,然后输出所有标签中的“字符串”内容;

for x in soup.find_all('a'):
    string = x.get_text()
    print(string)

运行结果:

Elsie
Lacie
Tillie

附:
另外,发现一篇总结的爬虫标签提取很不错,可以参考学习下。
https://www.cnblogs.com/simple-li/p/11253312.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Python 爬虫教程,可以批量爬取指定网站的图片: 首先,我们需要安装 requests 和 BeautifulSoup 这两个库。可以通过以下命令进行安装: ``` pip install requests pip install beautifulsoup4 ``` 接下来,我们需要编写代码。以下是一个示例代码,可以爬取指定网站的图片并保存到本地: ```python import requests from bs4 import BeautifulSoup import os # 爬取图片的网站 url = "https://www.example.com/" # 请求头,模拟浏览器访问 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} # 发送请求,获取网页内容 response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # 创建保存图片的文件夹 if not os.path.exists("images"): os.makedirs("images") # 遍历所有的图片标签,获取图片链接并保存到本地 for img in soup.find_all("img"): img_url = img.get("src") if img_url.startswith("http"): response = requests.get(img_url) with open("images/" + os.path.basename(img_url), "wb") as file: file.write(response.content) print("已保存图片:", img_url) ``` 在上述代码中,我们首先定义了要爬取的网站的 URL。然后,我们使用 requests 库发送一个 GET 请求,获取网页的 HTML 内容。接着,我们使用 BeautifulSoup 库对 HTML 进行解析,获取所有的图片标签。最后,我们使用 requests 库再次发送 GET 请求,获取图片的二进制数据,并保存到本地的 images 文件夹中。 注意,这里我们使用了一个 if 判断来过滤掉非 HTTP 开头的图片链接,以避免出现下载错误的情况。 为了更好的用户体验,代码中还加入了一些注释,方便大家理解。 希望这个简单的 Python 爬虫教程能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值