爬虫---

from urllib import request

import re

 

#定义url

page=100

url='http://tieba.baidu.com/f?kw=%E6%AE%B5%E5%AD%90&ie=utf-8&pn='+str(page)

 

try:

    #定义请求头

    headers={'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'}

    #定义请求 , 传入请求头

    req=request.Request(url,headers=headers)

    # 打开网页

    resp=request.urlopen(req)

    #打印响应,解码

    content=resp.read().decode('utf-8')

    print(content)

    # 正则表达式

    # pattern=re.compile(r'<title>(.*)</title>')

    # <a rel="noopener" 具体的东西直接写出

    # .*?匹配没用的数据

    # (.*?)匹配有用的数据的分组

    # \s 空格

    pattern=re.compile(r'<a rel="noopener".*?title=(.*?)\s.*?>(.*?)</a>')

    # 匹配HTML

    items=re.findall(pattern,content)

    # 打印解析的内容

    for i in items:

        print(i[0]+'\t'+i[1])

        # print('标题title:'+i[0]+' '+'content'+i[1])

        # print(1)

except request.URLError as e:

    # 打印响应码

    if hasattr(e,'code'):

        print(e.code)

    # 打印异常原因

    if hasattr(e,'reason'):

        print(e.reason)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值