zoukankan      html  css  js  c++  java
  • python爬虫第二天

    # 爬取糗事百科项目 由于该网站正在维护 我只是按照已经能够爬取出来的html代码手动观察修改正则表达式的内容

    # 代码

    # coding=utf-8
    # 导入相应库文件
    import requests
    # from bs4 import BeautifulSoup
    import re

    # 设置请求头(不知道为什么我这个请求头访问不了搜狐浏览器)
    # headers = { "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/
    # 75.0.3770.100 Safari/537.36"
    # }
    infoLists = []


    def get_info(url):
    res = requests.get(url)
    # print(res.content.decode("utf-8")) # 输出已经爬取得网页html代码
    ids = re.findall("<title>(.*?)</title>", res.content.decode("utf-8"), re.S)
    # print(ids) # 查看爬取结果
    levels = re.findall("<h1>(.*?)</h1>", res.content.decode("utf-8"), re.S)
    # print(levels) # 查看爬取结果
    for id, level in zip(ids, levels):
    infos = {
    "id":id,
    "level":level
    }
    infoLists.append(infos)
    # 注意ids和levels不能为空列表


    if __name__ == '__main__':
    urls = ["http://www.qiushibaike.com/text/page/{}/".format(i)for i in range(2, 3)]
    for url in urls:
    get_info(url)
    for infoList in infoLists:
    with open("qiushi.txt","a") as fileObject:
    try:
    fileObject.write(infoList["id"]+" ")
    fileObject.write(infoList["level"])
    print("写入成功")
    except Exception as e:
    print(e)
    print("输出出现错误")
    finally:
    pass

     # 函数解析

    re.findall(pattern, string, flags=0) 通过使用该函数可以匹配所有符合查询规律的内容  通过查询API文档可以发现 pattern是需要查询的格式类型,string

    是需要进行查询的字符串信息,flags是标志位可以对查询进行控制。

    re.S  使匹配包括换行符在内的所有字符 通过使用re.S可以进行多行匹配

  • 相关阅读:
    通过命令行指定 Java 程序运行时使用的字符集
    Ubuntu Linux 开启 root 用户及其它登录问题的解决
    SLF4J 的几种实际应用模式 SLF4J+Log4J 与 SLF4J+LogBack
    Java 获取当前时间的年月日方法
    Eclipse 全屏插件
    Linux 下的纯 C 日志函数库: zlog
    如何使用 Log4j
    DAO 设计模式
    为什么要用 /dev/null 2>&1 这样的写法
    NSDate和NSString之间的转换
  • 原文地址:https://www.cnblogs.com/walxt/p/11759164.html
Copyright © 2011-2022 走看看