0
点赞
收藏
分享

微信扫一扫

爬虫基础--

高子歌 2022-03-20 阅读 71
爬虫python

from urllib import request

import re

 

#定义url

page=100

url='https://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.51 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'<a.*?title=(.*?)\s.*?>(.*?)</a>')

    #匹配html

    items=re.findall(pattern,content)

    #打印解析的内容

    for i in items:

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

except request.URLError as e:

    #打印响应码

    if hasattr(e,'code'):

        print(e.code)

    #打印异常原因

    if hasattr(e,'reason'):

        print(e.reason)

举报

相关推荐

【爬虫基础_4】爬虫xpath

爬虫-Python基础

网络爬虫基础

爬虫基础_httpx

爬虫基础1

爬虫基础概述

0 条评论