爬虫准备
编写爬虫离不开requests和BeautifulSoup4
anaconda安装
下载地址:跳转官网首页,点Download按钮就可以下载
打开jupyter,点new,然后选择python3;你以为到这就结束了吗?
会发现创建失败,原因:没有配置环境!
环境配置完成,创建成功,然后就可以开始编程了。
相关方法
在jupyter中演示如下:
from bs4 import BeautifulSoup
html_sample='\
<html> \
<body> \
<h1 id="title">hello world</h1> \
<a href="#" class="link">This is link1</a> \
<a href="# link2" class="link">This is link2</a> \
</body> \
</html>'
soup = BeautifulSoup(html_sample)
print(soup.text)
print(soup.contents)
print(soup.select('html')[0])
# 标签选取
print(soup.select('h1'))
print(soup.select('h1')[0])
#第一个获取到的是列表,第二个获取到的是字符串
#id选取
print(soup.select('#title'))
print(soup.select('#title')[0])
# 类选取
print(soup.select('.link'))
print(soup.select('.link')[0])
print(soup.select('.link')[1])
实践是一切真理的唯一标准
以小米官网首页,试一试:
netword清空刷新页面,点开了index.html,可以看到requests method是get,所以复制url,打开jupyter进行以下操作:
import requests
res = requests.get("https://www.mi.com/index.html")
print(res.text)