10- 30简单爬虫 - 静态网页爬取

#爬取读者文章
#网页数据分为 动态网页数据和静态网页数据,两种网页数据的爬取是不一样的
#爬虫思路- 当前页面的网页源代码-其中获取需要的信息

import requests
	 #requests 是一个代码版的浏览器
from  bs4 import BeautifulSoup
	#数据的提取/解析 ,三大解析工具之一(万能的re)最简单的 bs4 

#1.目标路径
url='http://www.rensheng5.com/duzhewenzhai/rensheng/id-183982.html'

#2. 发送请求
resp=requests.get(url)  #模块的get方法
print(resp)
#<Response [200]> 表示二者间的通信正常的
html=resp.content.decode('gbk')

# resp.text 返回文本格式
# resp.content 二进制格式
print(resp.content.decode('gbk'))


#获取网页源代码后,提取想要的内容(专业术语-解析网页或者 数据提取)
#3.解析网页、数据提取
soup=BeautifulSoup(html,'lxml')
#lxml是一个解析库
print(soup)
#注意 print函数也有自己的编码格式,若不相同,可以使用专门语句修改输出函数的编码格式
# 修改print函数的编码格式语句 ,需要用的两个内置库 io和sys
# sys.stdout=io.TextIOWrapper(sys,stdout.buffer,encoding='gbk18030')



#soup的两个方法  
#find--找第一条满足条件的内容  返回str
#find_all-满足条件的所有内容   返回list

soup.find('li')

soup.find('div',class_="artview") 

soup.find('div',class_="artview").find('h1')


<h1>修养是一个人最体面的外衣</h1>

soup.find('div',class_="artview").find('h1').string
'修养是一个人最体面的外衣'

text=soup.find('div',class_="artview").find('h1').get_text()
print(text)
返回值:
	
	修养是一个人最体面的外衣


猜你喜欢

转载自blog.csdn.net/weixin_46400833/article/details/109395816
今日推荐