我们在安装py是建议如果使用windows不要安装原生的py因为windows的c编译器原因会使某些套件安装起来有麻烦
也就是安装anaconda版本的pyhttps://www.anaconda.com/download/#windows
py官网下载的是原生版本https://www.python.org/
本文爬取文字使用原生python进行演示
爬虫的原理就是模仿人类登录不同的网页 然后使用开发者工具来获得服务器传回的信息 将其按照特定格式储存起来
简单说就是ETL(数据获取extract,数据转换translation,数据保存loading)
如果文中的代码直接复制进py的编辑器会打乱 呢就先copy到notepad++ 然后在copy到编辑器就ok了
我们以chrome浏览器为示例
首先我们打开一个页面右键检查 或者使用f12
点击刷新/或按下f5我们可以看到服务器返回的内容
我们可以看到 我们需要的内容
这里可以看到一个get我们要注意这里有了这些经验我们就可以开始利用无所不能的python来完成这些过程
我们在安装过程中一定要注意是在cmd下安装不能再python环境下安装!!!
py环境会失败
打开cmd输入
pip install requests
pip install beautifulsoup4
同理安装 anaconda 的库
然后安装jypyter
下面安装完成后只需要输入
会自动打开浏览器 我们通过一个port访问自己电脑 然后可以创建python的项目
下面我们开始写一个程序模拟人类点击的过程
但是因为我们爬取文字等拿原生py就可以做到我们就不使用anaconda作为案例了
下面我们打开notepad++这个文本编辑器有中文版并且免费
https://notepad-plus-plus.org/
或者直接使用py的idle交互式编译器
在这里直接复制网址
我们运行就可以获取获取网页html的所有内容
这样我们的第一只爬虫就写好了,但是怎样获取到我们需要的信息呢?
import requests
res = requests.get('http://www.jinyongwang.com/shen/781.html')
res.encoding = 'utf-8'
print(res.text)
点击f5运行我们会发现程序会卡死这是因为我们打开的文字太多了
所以我们需要将爬取的文字放入二进制文件
并且删除标签 选择正确的内容
现在我们强行关闭shell
加入代码可以爬出前500行的代码
import requests
url='http://www.jinyongwang.com/shen/781.html'
r = requests.get(url,timeout=30)
type(r) #查看类型
print(r.text[:500]) #显示前500字节内容
print(r.status_code) #显示状态码
下面我们使用beautifulsoup
先来看html的结构
bs4套件的使用模板
import requests
from bs4 import BeautifulSoup
url = 'https://python123.io/ws/demo.html'
r = requests.get(url,timeout=30)
r.encoding = r.apparent_encoding
#分析页面内容,以中文编码显示
html = r.text
soup = BeautifulSoup(html, 'html.parser')
#访问head、body、a、p、b
soup.find_all(‘a’)、soup.body.contents、soup.prettify()
使用beautifulsoup寻找标签
url = http://news.qq.com/a/20170504/012032.htm
div.hd L131
div.a_info L135
P.text L164
title = soup.select("div.hd > h1")
time = soup.select("div.a_Info > span.a_time")
paras = soup.select("div.Cnt-Main-Article-QQ > p.text")
我们注意py中是不需要声明变量的
寻找特定的HTML标签
找到h1标签的文本
soup = BeautifulSoup(html_sample)
header = soup.select('h1') #h1可以改成任意标签
print(header)
print(header[0]) #去除中括号保留标签和文本
print(header[0].text) #去除标签保留文本
寻找特定css元素
id类
id名前加#
alink = soup('#title')
print(laink)
class类
class名前加.
soup = BeautifulSoup(html_sample)
for link in soup.select('.link'):
print(link)
取得标签中的属性
取得所有a标签的链接
a tag找出所有herf(超链接)的链接
a = '<a herf="#" qwe=123 asd=456>i am a link</a>'
soup = BeautifulSoup(a,'html.parser')
print(soup.select('a')[0]['href'])
print(soup.select('a')[0]['qwe'])
保存文本文件
fo = open("text.txt", "w+")
fo.writelines(title[0].get_text() + "\n")
fo.writelines(time[0].get_text() + "\n")
for para in paras:
if len(para) > 0:
fo.writelines(para.get_text() + "\n\n")
fo.writelines(author[0].get_text() + '\n')
fo.close()
于是我们将代码结合写出一个爬虫将小说写入二进制文件中
import re
import requests
from bs4 import BeautifulSoup
def getHTML(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def getContent(url):
html = getHTML(url)
soup = BeautifulSoup(html,'html.parser')
title = soup.select('div.mbtitle')
paras_tmp = soup.select('p')
paras = paras_tmp[3:]
return paras
def saveFile(text):
f=open('novel.txt','w')
for t in text:
if len(t) > 0:
f.writelines(t.get_text() + "\n\n")
f.close()
def main():
url = 'http://www.jinyongwang.com/shen/781.html'
text = getContent(url)
saveFile(text)
main()
运行完出现我们需要的文档
打开就是我们需要的文本了