02. 爬虫之bs4模块

一、爬取汽车之家新闻

# request模块(发送请求)+bs4(解析html的模块)
# 汽车之家为例

# 环境依赖
- pip3 install beautifulsoup4
- pip3 install lxml

import pymysql
import requests
from bs4 import BeautifulSoup
res=requests.get('https://www.autohome.com.cn/news/1/#liststart')
print(res.text)

# 类实例化(第一个参数,要解析的html内容,第二个参数是使用的解析器)
# html.parser :bs4的内置解析器
# lxml        :额外装lxml(快)
# soup=BeautifulSoup(res.text,'html.parser')
soup=BeautifulSoup(res.text,'lxml')
conn=pymysql.Connect(host='127.0.0.1', user='root', password="123",database='qc', port=3306)
cursour=conn.cursor()

# find: 找一个
# find_all: 找所有
# 因为class是关键字,所以使用class_
ul_list=soup.find_all(name='ul',class_='article')
for ul in ul_list:
    li_list=ul.find_all('li')
    for li in li_list:
        h3=li.find('h3')
        if h3:
            # 取出h3标签的文本内容
            title=h3.text
            desc=li.find(name='p').text
            url='https:'+li.find(name='a')['href']
            photo_url='https:'+li.find(name='img')['src']
            print('''
            新闻标题:%s
            新闻链接:%s
            新闻图片:%s
            新闻摘要:%s
            '''%(title,url,photo_url,desc))

            # 把图片保存到本地
            res=requests.get(photo_url)
            name=photo_url.split('_')[-1]
            with open('imgs/%s'%name,'wb') as f:
                for line in res.iter_content():
                    f.write(line)
            # 入库mysql
            sql='insert into article (title,url,photo_url,`desc`) values(%s,%s,%s,%s);'
            cursour.execute(sql,args=[title,url,photo_url,desc])


conn.commit()  # 提交
cursour.close()
conn.close()

二、bs4模块之遍历文档树

'''
#遍历文档树:即直接通过标签名字选择,特点是选择速度快,但如果存在多个相同的标签则只返回第一个
#1、用法
#2、获取标签的名称
#3、获取标签的属性
#4、获取标签的内容
#5、嵌套选择
#6、子节点、子孙节点
#7、父节点、祖先节点
#8、兄弟节点
'''

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_pp' name='lqz'>asdfasdf<b>asdfas</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'lxml')

### 遍历文档树(速度快)

### 1、用法
head = soup.head
print(head)
print(type(head))

p = soup.body.p
# p = soup.p  # 速度没有上面的快,数据越大越明显(查找不够精准)
print(p)

### 2、获取标签的名称
p = soup.p.name  # 对象.name 取到标签的名字
print(p)

### 3、获取标签的属性
p=soup.p['class']   # class 是列表,可以有多个
name=soup.p['name']

attr=soup.p.attrs  # 所有属性放到字典中
print(attr)


### 4、获取标签的内容
t=soup.p.text  # 把p标签文本+子标签文本都拿出来
print(soup.p.string) # p下的文本只有一个时,取到,否则为None
print(soup.p.strings) # 拿到一个生成器对象, 取到p下所有的文本内容
print(list(soup.p.strings)) # 拿到一个迭代器对象, 取到p下所有的文本内容

### 5、嵌套选择
b=soup.body.p.b
print(b)

三、bs4模块之搜索文档树

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_pp' name='lqz'>asdfasdf<b>asdfas</b><span>span<b>bbb</b></span></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister1" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup=BeautifulSoup(html_doc,'lxml')

# find和find_all的用法:用法完全一样,只不过find找到第一个,find_all找到所有

# 5种过滤器:字符串、正则表达式、列表、True、方法

# 字符串:name:标签名   class_:类名  id:id号  href:href
# 只要是BeautifulSoup对象Tag的对象,可以继续find,继续遍历 . 找
# res=soup.find(name='body').p
# res=soup.find(name='body').find(name='p')
# print(type(res))
# print(res)

# res=soup.body.find(id='link2')
# res=soup.body.find(href='http://example.com/lacie')
# res=soup.body.find(name='a',href='http://example.com/lacie')
# print(res)


# 列表

# res=soup.find_all(name=['a','p'])
# res=soup.find_all(id=['link2','link3'],class_='sister')
# print(res)


# 正则表达式
# import re
# # res=soup.find_all(name=re.compile('^b'))
# res=soup.find_all(class_=re.compile('^s'),name='a')
# print(res)

# True
# res=soup.find_all(name=True)
# res=soup.find_all(class_=True)
# res=soup.find_all(id=True)

# res=soup.find_all(href=True)
# for i in res:
#     url=i['href']
#     print(url)

# print(res)



# 方法(了解)
# def aaa(tag):
#     # return tag.has_attr('class') and not tag.has_attr('id')
#     return tag.has_attr('class') and  tag.has_attr('id')
#
# res=soup.find_all(name=aaa)
# print(res)

四、find_all的其他参数

# find的其它参数
#attrs
# res=soup.find_all(attrs={'id':'link1'})
# res=soup.find_all(id='link1')


# recursive 是否递归查找,只找一层
# res=soup.body.find_all(id='bb',recursive=False)
# res=soup.body.find_all(id='bb')

# text 文本内容(5种过滤器)
# res=soup.body.find_all(text='asdfas')[0].parent



# limit
# res=soup.body.find_all(True)
res=soup.body.find_all(name=True,limit=1)

soup.find()
print(res)

五、css选择器

# css选择器

'''

#id_p   :#id号
.class1 :.类名
body    :标签名
p>b     :p的亲儿子b
p b     :p的的后代b

'''
# select写css选择器  通用的(bs4,selenium,lxml)
# res=soup.select('body>p')
# res=soup.select('body p')
# res=soup.select('#link1')
# print(res)

# css选择器可以之间copy
# #maincontent > h1
#


# 2、获取属性
# print(soup.select('#link1')[0].attrs)
# # print(type(soup.select('#link1')[0]))
# print(soup.select('#link1')[0].text)

# 3、获取内容
# print(soup.select('#list-2 h1')[0].get_text())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值