理解爬虫原理
1. 简单说明爬虫原理
上网所看到页面上的内容获取下来,并进行存储。
2. 理解爬虫开发过程
1).简要说明浏览器工作原理;
浏览器发送请求,服务器接收到,给出响应。
2).使用 requests 库抓取网站数据;
url= 'http://www.sohu.com/' res = requests.get(url)
3).了解网页
<html> <body> <h1 id="title">Hello</h1> <a href="#" class="link"> This is link1</a><a href="# link2" class="link" qao=123> This is link2</a> <p id="info">This is info </body> </html>
4).使用 Beautiful Soup 解析网页;
通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
soup = BeautifulSoup(res.text,'html.parser')
select(选择器)定位数据
t = soup.select('#title')
l = soup.select('.link')
找出含有特定标签的html元素
t = soup.select('h1')[0].text
print(t)
找出含有特定类名的html元素
for i in range(len(soup.select('.link'))):
d = soup.select('.link')[i].text
print(d)
找出含有特定id名的html元素
info = soup.select('#info')[0].text
print(info)
3.提取一篇校园新闻的标题、发布时间、发布单位
import requests
import bs4
from bs4 import BeautifulSoup
url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0322/11049.html'
res = requests.get(url)
res.encoding='utf-8'
soup = BeautifulSoup(res.text,'html.parser')
title = soup.select('.show-title')[0].text
print(title)

time = soup.select('.show-info')[0].text
print(time)

浙公网安备 33010602011771号