0
点赞
收藏
分享

微信扫一扫

极简爬虫通用模板

网络爬虫的一般步骤如下:

1、确定爬取目标:确定需要爬取的数据类型和来源网站。

2、制定爬取策略:确定爬取哪些网页、如何爬取和频率等。

3、构建爬虫程序:使用编程语言(如Python)实现爬虫程序,通过HTTP请求获取网页内容,并进行解析和处理。

4、数据存储:将爬取到的数据存储到数据库或文件中,便于后续处理和分析。

5、处理异常情况:处理因网络故障、网页解析错误等原因导致的异常情况。

6、遵守规则:遵守网络爬虫的相关规定,如robots协议、网站的访问频率限制等。

7、定期更新:定期更新爬虫程序,以适应网站的变化和更新。

极简爬虫通用模板_爬虫模板

一、准备工作

1、获取网页

需要用到requests库,最常用得是get()方法

import requests
link = 'https://网址xxxxx/'
response  = requests.get(link)

这样就获取了网页,想要进一步查看网页,需要用到text属性

print(response.text)`

2、解析网页(也就是找到想要的信息)

需要用到bs4库

from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text,'html.parser')

找到对应标签需要用到find_all方法

soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")

3、保存信息

with open('book.txt','a+') as f:
        f.write(m.text+'\n')

二、爬虫程序最小框架

结合上面所说,爬虫最小框架得代码为

import requests
from bs4 import BeautifulSoup
# 获取网页
link = 'https://网址xxxxx/'
response  = requests.get(link)
# 解析网页
soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
# 保存信息
with open('book.txt','a+') as f:
    f.write(m.text+'\n')

三、额外说明

为了顺利爬取网站信息,有几个必备技能一定要了解。

1、headers

为了对付“反爬虫”,我们需要让程序觉得是人在操作,最基本得方法是设置headers

headers = {'User-Agent': 'xxx此处换为自己的信息xxxx'}
link = 'https://网址xxxxx/'
response  = requests.get(link ,headers = headers)

2编码方式设定

有时候爬取下来得信息会出现乱码,这时候需要通过设置编码解决。常见得编码方式为UTF-8、GBK

response  = requests.get(link ,headers = headers)
response.encoding = 'UTF-8'

所以我们得爬虫最小框架进化成了下面得形式

import requests
from bs4 import BeautifulSoup
# 获取网页
headers = {'User-Agent': 'xxx此处换为自己的信息xxxx'}
link = 'https://网址xxxxx/'
response  = requests.get(link ,headers = headers)
response.encoding = "UTF-8"
# 解析网页
soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
# 保存信息
with open('book.txt','a+') as f:
    f.write(m.text+'\n')

四、举例

举例子。此处需要把headers设置成自己得才能正常运行。

import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'xxx此处换为自己的信息xxxx'}
link = 'http://jshk.com.cn/'
response  = requests.get(link ,headers = headers)
response.encoding = 'UTF-8'
print(response.text)
soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
for n in soup:
   n = n.find_all(name='a')
   for m in n:
       with open('book.txt','a+') as f:
           f.write(m.text+'\n')

举报

相关推荐

0 条评论