网络爬虫requests和bs4简单入门

网络爬虫基础(嵩天老师爬虫教学)

本博客的主要内容:介绍如何使用基本的库完成对html页面内容的爬取和分析,分以下几方面介绍

  1. 介绍网络爬虫的基本工作过程
  2. requests库的基本用法
  3. 使用BeautifulSoup对页面进行解析
1.介绍网络爬虫的基本工作过程

The Website is the API 我们应该将网页看成是一个我们获取信息的接口,我们可以通过python爬虫从中获取我们所需要的信息。
一般步骤:
(1)通过requests库爬取html页面的内容
(2)使用BeautifulSoup库对爬取到的html页面进行解析
(3)使用BeautifulSoup以及正则表达式来进一步提取我们想要的关键信息
(4)将信息格式化并输出

2.requests库的基本使用

requests库有好几种方法,这里我们介绍最主要的get和post方法
最简单的请求方法get:

import requests
r  = requests.get("http://python123.io/ws/demo.html")
print(r)
<Response [200]>    #返回码200表示访问正常
r.encoding = r.apparent_encoding   #使用该语句将正确的编码给到 r 
r.text    #打印出html页面的内容
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>'

以上说明成功访问了,但是存在一些网站我们通过以上的操作访问不成功,且手动点击却可以访问成功。大概率是因为我们的请求头的原因,看一下我们的请求头

r.request.he
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值