百度一下,你就知道 ![]()
百度热搜 换一换 0 多措并举助企稳就业 3 山东舰霸气壁纸 1 河南村镇银行多位储户称又被赋红码 4 通信行程卡时间范围由14天改为7天 2 约翰逊辞职后谁将接唐宁街烂摊子 5 山东新增66例本土无症状 在临沂 关于百度 About Baidu 京公网安备11000002000001号 京ICP证030173号 药品医疗器械网络信息服务备案(京)网药械信息备字(2021)第00159号 ^
*{
margin: 0;
padding: 0;
}
.top{
margin-top: 10px;
width: 1200px;
height: 30px;
}
.top_left{
float: left;
}
.top_right{
float: right;
}
a{
color: black;
text-decoration: none;
font-size: 5px;
margin-left: 20px;
}
.top_right > a,.top_right > input{
margin-right: 10px;
}
.top_right > input{
width: 44px;
height: 20px;
background-color: rgba(61,83,239,0.9);
color: white;
border: 0px;
border-radius: 6px;
font-size: 1px;
}
.center{
width: 1200px;
text-align: center;
}
.center > div:nth-child(2) > .input_text{
border: 2px solid lightgray;
border-right: 0px;
border-radius: 10px 0 0 10px;
width: 450px;
height: 30px;
}
.center > div:nth-child(2) > .button{
border: 0px;
border-radius: 0 10px 10px 0;
background-color: rgba(61,83,239,0.9);
color: white;
width: 80px;
height: 34px;
margin-left: -6px;
}
table{
width: 530px;
text-align: left;
margin-top: 30px;
margin-left: 28%;
font-size: 1px;
}
td{
height: 30px;
}
.bottom{
width: 1200px;
text-align: center;
font-size: 1%;
position: absolute;
bottom: 2px;
}
爬虫
requests — 请求页面,得到响应结果
BeaytifulSoup — 根据响应结果解析页面、提取结果
# 写入文件、数据库 import requests from bs4 import BeautifulSoup
bs4模块能够从html或者xml中提取数据
for page in range(1, 11):
print(f'这是第{page}页')
URL = f'https://www.chinanews.com.cn/scroll-news/news{page}.html'
header = {} —> headers是一个字典:{key:value}
headers是给爬虫提供伪装的
User-Agent —> 将爬虫伪装为浏览器
Headers = {
'User-Agent':''
}
response = requests.get(url=URL)
# 如果状态码 = 200,爬虫可用
if response.status_code == 200:
response.encoding = 'UTF-8'
为什么要对比打印结果和网页中的内容是否一致?
网页:分为静态页面和动态页面
静态页面:内容是写死的,除非人为的进行内容修改,否则这个页面的内容是一成不变的
动态页面:内容不是写死的,使用某种特殊的技术(JavaScript)使页面中的数据通过某种方式显示在页面中
requests得到的结果是静态页面的结果
- BeautifulSoup(网页源码,解析器) —> 将字符串类型的源代码转换为BS4类型
- bs4模块提供了一系列提取数据的方法,这些方法的操作对象的bs4类型的数据
soup = BeautifulSoup(response.text, "html.parser")
- select:根据CSS选择器(标签、class、id等)定位数据,
得到的是符合这个选择器的所有结果(整体是列表,列表中每个元素是一个bs4类型的数据) - select_one:根据CSS选择器(标签、class、id等)定位数据,
得到的是符合这个选择器的一个结果(是一个bs4类型数据) - text:从bs4类型数据中提取标签内的内容,结果为str
- attrs:从bs4类型数据中提取标签内容属性值,结果为str
li_list = soup.select('body > div.w1280.mt20 > div.content-left > div.content_list > ul > li')
# print(li_list)
for i in li_list:
if i.select_one('li > div.dd_lm > a') != None:
news_type = i.select_one('li > div.dd_lm > a').text
print(news_type)
news_title = i.select_one('li > div.dd_bt > a').text
print(news_title)
news_href = 'https://www.chinanews.com.cn' + i.select_one('li > div.dd_bt > a').attrs['href']
print(news_href)
news_time = i.select_one('li > div.dd_time').text
print(news_time)
…
生活
世界过敏性疾病日:长期熬夜可加重皮肤过敏
https://www.chinanews.com.cn/life/2022/07-08/9798520.shtml
7-8 10:08
生活
怎样改造老人的家才能适合老人家?
https://www.chinanews.com.cn/life/2022/07-08/9798515.shtml
7-8 10:07


