第一、下载安装 BeautifulSoup
pip install beautifulsoup4
第二、编写爬虫爬百度搜索右边热点数据
import requests
from bs4 import BeautifulSoup
"""
python3.8.1 入门基础学习 之 【 BeautifulSoup 基础学习,python3 爬虫爬百度搜索右边 搜索热点 数据】
"""
def fistRequestAdnBs4():
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36'
}
# 设置URL,设置headers,设置请求超时时间5秒
r = requests.get('https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=%E4%B8%89%E4%BA%91%E6%97%B6%E5%85%89&rsv_spt=1&oq=pip%2520install%2520request&rsv_pq=9541ec1100013a70&rsv_t=58b7oO00R1U4nVBJ1beD2LdZqHA%2B9Net20g9dO%2Ffs3T5x%2BM7nLjmsDJ1hkfFDMtakJaX&rqlang=cn&rsv_enter=1&rsv_dl=tb&inputT=5842&rsv_sug3=32&rsv_sug1=23&rsv_sug7=100&rsv_sug2=0&rsv_sug4=9553',
headers=headers, timeout=5)
if r.ok: # 请求是否成功
soup = BeautifulSoup(r.content,"html.parser") # 解析HTML
table = soup.find("table") # 获取百度搜索页面最右边的 搜索热点 列表
lista = table.tbody.find_all("a") # 获取热点链接
for child in lista: # 循环遍历 热点列表数据集合
print(child.string) # 打印热标签内容
else: # 请求出错
print("请求失败")
if __name__ == '__main__':
fistRequestAdnBs4()
4、学习更多更详细的 BeautifulSoup 使用文档,请查阅官方文档
https://beautifulsoup.readthedocs.io/zh_CN/latest/
最后修改于 2020-01-03 21:51:48
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

