Loading

BeautifulSoup4介绍及使用、爬取新闻

BeautifulSoup4 介绍

# Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库
# 使用requests发请求拿回来的html,就可以使用bs4解析出咱们想要的数据

# BeautifulSoup(要解析的字符串, "解析方式:html.parser,lxml:需要安装lxml解析库,如果不装就报错")

# 文档容错能力:可以不是标准的html,缺一些标签,也可以解析

bs4 遍历文档树

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p'>lqz is handsome<b>The Dormouse's story</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,'html.parser')
# print(soup.prettify())  # 美化html


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

'''

# 1 基本使用(通过 . 遍历,速度快)
# res=soup.p
# res1=soup.p.b
# res1=soup.html.body.p.b
# print(res1)

# 2 取标签的名称
# res1=soup.body
# print(res1.name)

# 3 获取标签的属性(两种方式)
# res1=soup.body.p
# # print(res1['class'])   # ['title']  因为class可能有多个
# # print(res1['id'])
# print(res1.attrs['id'])

# res=soup.a['href']
# print(res)


# 4 获取标签的内容
# res=soup.a
# print(res.text)  # text 把子子孙孙的文本内容拼到一起
# print(res.string) # string 没有子标签才能获取文本
# print(list(res.strings))  # generator strings:把子子孙孙的文本内容放到生成器中

# res=soup.p
# print(res.text)
# print(res.string)
# print(list(res.strings))


#5、嵌套选择(因为soup.head那到的也是要给对象,bs4.element.Tag类的对象,因为BeautifulSoup继承子Tag)
# print(soup.head.title.string)
# print(type(soup.head))


### 一下的了解
#6、子节点、子孙节点
# print(soup.p.contents) # p下所有子节点
# print(soup.p.children) #得到一个迭代器,包含p下所有子节点
# print(list(soup.p.descendants)) #获取子孙节点,p下所有的标签都会选择出来


#7、父节点、祖先节点
# print(soup.a.parent) #获取a标签的父节点
# print(list(soup.a.parents)) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...

#8、兄弟节点
# print(soup.a.next_sibling) #下一个兄弟
# print(soup.a.previous_sibling) #上一个兄弟
#
# print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
# print(list(soup.a.previous_siblings)) #上面的兄弟们=>生成器对象

bs4搜索文档树

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p'>lqz is handsome<b class='sister'>The Dormouse's story</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, 'html.parser')

# find(找最近的一个),find_all(找所有符合的)

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

#  1 字符串--->字符串指的是属性是字符串
# p=soup.find(name='p',class_='title')
# p=soup.find(id='id_p')
# p=soup.find(id='id_p')
# res=soup.find(text="The Dormouse's story").parent
# print(res)


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

# 3 列表
# res=soup.find_all(name=['body','b'])
# res=soup.find_all(class_=['sister','story'])
# print(res)

# 4 True
# res=soup.find_all(id=True)  # 有id的所有标签
# res=soup.find_all(text=False)
# print(res)


# 5方法
# def has_class_but_no_id(tag):
#     return tag.has_attr('class') and not tag.has_attr('id')
#
# print(soup.find_all(name=has_class_but_no_id))


# find_all的其它属性:find就是find_all,只不过取了第一条
# limit:限制取的条数
# res=soup.find_all(class_=True,limit=1)
# recursive:是否递归查找,找一层还是找多层
# res=soup.body.find_all(name='p',recursive=False)

# attrs
# res=soup.find_all(class_=True)
# res=soup.find_all(attrs={'class':True})
# print(res)



# 搜索文档树的方式使用的是find和find_all

css选择器

# 还可以使用css选择器
'''
div    标签名
.类名   类名
#id     id号
div>p   div下紧邻的p标签
div p   div下子子孙孙有p就拿出来

'''
# res=soup.select('.sister')
# res=soup.select('b.sister')
res=soup.select('#id_p')[0]['class']
print(res)

爬取新闻

# re 正则匹配----》html内容(xml),比较复杂,查找的东西比较多,BeautifulSoup4 专业的对html,xml进行解析(修改)
# pip3 install beautifulsoup4
import requests
import pymysql

pymysql.install_as_MySQLdb()
conn_obj = pymysql.connect(
    host='127.0.0.1',  # MySQL服务端的IP地址
    port=3306,  # MySQL默认PORT地址(端口号)
    user='root',  # 用户名
    password='123',  # 密码  也可以简写 passwd
    database='xinwen',  # 库名称  也可以简写 db
    charset='utf8'  # 字符编码 千万不要加杠utf-8
)  # 要善于查看源码获取信息
cursor = conn_obj.cursor()
from bs4 import BeautifulSoup

ip = requests.get('http://127.0.0.1:5010/get/').json()
# print(ip['proxy'])
if ip['https']:
    h = 'https'
else:
    h = 'http'

proxies = {
    h: ip['proxy'],
}
for i in range(100):
    try:
        res = requests.get('https://www.autohome.com.cn/news/%s/#liststart' % i, proxies=proxies)
        soup = BeautifulSoup(res.text, 'html.parser')
        ul_list = soup.find_all(name='ul', class_='article')
        for ul in ul_list:
            li_list = ul.find_all(name='li')
            for li in li_list:
                h3 = li.find(name='h3')
                # print(h3)
                if h3:
                    title = h3.text
                    # print(title)
                    desc = li.find('p').text
                    # print(desc)
                    img = li.find('img').attrs.get('src')
                    # print(img)
                    if 'https:' not in img:
                        img = 'https:' + li.find('img').attrs.get('src')
                    # print(img)
                    url = 'https:' + li.find('a').attrs.get('href')
                    # print('''
                    # 新闻标题:%s
                    # 新闻摘要:%s
                    # 新闻地址:%s
                    # 新闻图片:%s
                    # ''' % (title, desc, url, img))
                    # 1 把图片保存到本地(你会)
                    # 2 把清洗过后的数据存到mysql中
                    # 3 全站爬取变更页码数(https://www.autohome.com.cn/news/1/#liststart)
                    sql = "INSERT INTO `xinwen`.`xinwenxinxi` ( `title`, `desc`, `url` )VALUES('%s', '%s', '%s'); " % (
                        title, desc, url)
                    # values = pymysql.escape_string(title),pymysql.escape_string(desc),pymysql.escape_string(url)
                    cursor.execute(sql)
                    conn_obj.commit()
    except:
        print('错误!!!')

posted @ 2022-08-03 18:22  香菜根  阅读(154)  评论(0编辑  收藏  举报