BeautifulSoup模块

BeautifulSoup是一个HTML/XML的解析器,主要的功能是如何解析和提取 HTML/XML 数据。简单来说,BeautifulSoup只是一个从html字符串提取数据的工具。

在这里插入图片描述

页面爬虫思路:

  • 1、导入模块
  • 2、定义URL和请求头参数
  • 3、requests发送html请求,获取html字符串
  • 4、实例化BeautifulSoup对象(中介)
  • 5、获取数据
  • 6、存储数据

实例一:微博热搜爬虫

在这里插入图片描述

import requests
from bs4 import BeautifulSoup

#定义URL和请求头
url='https://s.weibo.com/top/summary?display=0&retcode=6102'
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
}

#发送请求
response=requests.get(url=url,headers=headers)
content=response.content.decode('utf8')

#实例化BeautifulSoup对象
soup=BeautifulSoup(content,'lxml')	#指定解析器为lxml

#提取数据
sinas=[]
tds=soup.find_all('td',class_="td-02")[1:]      #提取“td”标签
#注意:Python中class是关键字,定义“类”,即属性名称和python关键字冲突。
#对class=‘ ’,在属性名语法错误。 称后添加一个下划线_即可。即class_=‘ ’

# print(tds)
for td in tds:
    event=td.find_all('a')[-1].string   #find_all()的结果是列表,[0]表示将内容提取出来
    hot=td.find_all('span')[0].string     #.string可把内容提取出来,去掉标签或标签属性等

    #将提取的数据以字典的形式存储
    sina={
        "event":event,
        "hot":hot,
    }
    sinas.append(sina)

print(sinas)

实例二:汽车之家新闻资讯爬虫

  • 爬取的数据:新闻标题、发表时间、新闻概要。
    在这里插入图片描述
import requests
from bs4 import BeautifulSoup

headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
}

urls=[]
for i in range(1,6):
    url="https://www.autohome.com.cn/news/{}/#liststart".format(i)
    urls.append(url)

#遍历所有URL
news=[]
for url in urls:
    try:
        #发送请求
        response=requests.get(url=url,headers=headers)
        content=response.text
        # print(content)

        # 实例化BeautifulSoup对象
        soup=BeautifulSoup(content,'html.parser')
        divs=soup.find_all('div',class_="article-wrapper")
        # print(divs)
        for div in divs:
            title=list(div.find_all('h3'))
            times=list(div.find_all('span',class_="fn-left"))
            profiles=list(div.find_all('p'))
            # print(title,times,profiles)
            for title,times,profiles in zip(title,times,profiles):	#批量处理循环的变量。
                title=title.string  #取字符
                times=times.string
                profiles=profiles.string
                # print(title,times,profiles)
                car_news={
                    "title":title,
                    "times":times,
                    "profiles":profiles,
                }
                news.append(car_news)
    except:
        continue
print(news)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值