• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
戈瑾
博客园    首页    新随笔    联系   管理    订阅  订阅
Python学习——爬虫

第一步:获取页面

首先导入import requests,使用requests.get(link,headers=headers)获取网页

注意:用requests的headers伪装成浏览器访问,我们要获得的信息在response.text里(就是网页的内容代码)

第二步:提取想要的数据

这里会用到BeautifulSoup这个库对爬下来的页面进行解析,将html代码转化为soup对象,接下来用find去寻找自己的数据

第三步:存储数据

存储到本地的txt文件,将获取的信息写入txt里,这里要特别注意格式encoding='utf-8',否则到txt里的东西会乱码

m bs4 import BeautifulSoup
import requests, sys
import random
#1.获取网页代码
url = 'https://www.cnblogs.com/znjy/'  #请求地址
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}#创建头部信息
response =  requests.get(url,headers = headers)  #发送网络请求

#print(response.text)
#2.提取想要的数据
soup=BeautifulSoup(response.text,"html.parser")
title=soup.find("a",class_="postTitle2").text.strip()
print(title)
time=soup.find("div",class_="dayTitle").a.text.strip()
print(time)
#3.写入到文件里
with open("title.txt","a+",encoding='utf-8') as f:
    f.write(time+":"+title)
    f.close()

 

posted on 2021-03-25 09:43  戈瑾  阅读(32)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3