zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    基于雪花算法的单机版
    Spring cloud gateway自定义filter以及负载均衡
    logback转义符与MDC
    录音地址文件保存
    maven加载本地jar
    ES Log4J配置信息
    java线程池
    openstreetmap的数据下载
    php更新版本后(路径更改后)要做的调整
    重启IIS
  • 原文地址:https://www.cnblogs.com/znjy/p/14906094.html
Copyright © 2011-2022 走看看