# 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]withopen('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下的文本只有一个时,取到,否则为Noneprint(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)