Python-如何食(使)用美丽汤(BeautifulSoup)?

1.安装

pip install beautifulsoup4

2.安装爬虫解析器lxml,因为它比较快,但也可以使用默认的parser

pip install lxml

3.导入

from bs4 import BeautifulSoup4
import requests

4.设置url,请求头headers。User-Agent

url = "想爬网站的网址"
headers = {“User-Agent”:“Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36”}

开爬!

response = requests.get(url,headers=headers)

5.设置编码为中文

response.encoding = 'utf-8'

6.设置Soup对象,解析器用lxml,把爬到的response内容text一下。

page = BeautifulSoup(response.text, 'lxml')

7.用find_all方法爬取标签,可以print一下,find_all是爬全部标签。

page.find_all('标签')

8.如果爬取到的html很乱的话可以使用prettify方法

page.prettify()

设置格式化输出

但在用beautifulsoup爬虫时遇到过一个问题,就是不能获取html中的指定节点。

所以可以用到attrs方法。content可以理解为html中的meta标签,再用attrs方法爬到标签中的指定节点

content = page.meta
print(content.attrs.get('content'))

再进行爬取时,也可以用next_sibling方法选择节点

page.'标签'.next_sibling

实例:爬取csdn个人信息

爬取csdn个人擅长领域。

import requests
from bs4 import BeautifulSoup
URL = 'https://blog.csdn.net/Sunyoho?spm=1001.2014.3001.5343'
head = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78'
}
html = requests.get(url=URL, headers=head)
html.encoding = 'utf-8'
page = BeautifulSoup(html.text, 'lxml')
page.prettify()
print(page.title.string)
content = page.meta.next_sibling.next_sibling
print(content.attrs.get('content'))

总结

        有些网站爬虫时很难找到json文件,但是beautifulsoup采取的是直接爬取网站html利用解析器进行分析。成功,靠滴是技术!

 

  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值