python02

02

转自老师总结:
1)选着要爬的网址 (url)
2)使用 python 登录上这个网址 (urlopen等)
3)读取网页信息 (read() 出来)
4)将读取的信息放入 BeautifulSoup
5)使用 BeautifulSoup 选取 tag 信息等 (代替正则表达式)
beautifulSoup下载安装
# Python 2+
pip install beautifulsoup4

# Python 3+
pip3 install beautifulsoup4
开始学习使用bs4

由于使用的是python,红线alt+enter+Install就可以解决下载安装。
接下来是常规的爬取模式。

from bs4 import BeautifulSoup
from urllib.request import urlopen

# if has Chinese, apply decode()
html = urlopen("https://mofanpy.com/static/scraping/basic-structure.html").read().decode('utf-8')
print(html)

print出来的结果

<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>Scraping tutorial 1 | 莫烦Python</title>
    <link rel="icon" href="https://mofanpy.com/static/img/description/tab_icon.png">
</head>
<body>
    <h1>爬虫测试1</h1>
    <p>
        这是一个在 <a href="https://mofanpy.com/">莫烦Python</a>
        <a href="https://mofanpy.com/tutorials/scraping">爬虫教程</a> 中的简单测试.
    </p>

</body>
</html>
soup = BeautifulSoup(html,features='lxml')
print(soup.h1)
<h1>爬虫测试1</h1>

如果网页中有过个同样的 tag, 比如链接<a>,可以使用find_all() 来找到所有的选项,用 key 来读取l["href"].

all_href = soup.find_all('a')
all_href = [l['href'] for l in all_href]
print('\n',all_href)

print出来的结果

 ['/', '/tutorials/data-manipulation/scraping/']
个人总结
1)import bs4,使用`bs4(beautifulSoup4)`以`lxml`进行加载,
2)直接选择相关标签进行打印
3)使用`l['']`配上for遍历进行以key为基础的遍历源码获取相关项进行打印
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值