python——简单的爬虫

1.了解网页结构

首先选取一部分的种子URL,将这些URL放入待抓取URL队列;

取出待抓取URL,解析DNS得到主机的IP,并将URL对应的网页下载下来,存储进已下载网页库中,并且将这些URL放进已抓取URL队列。

分析已抓取URL队列中的URL,分析其中的其他URL,并且将URL放入待抓取URL队列,从而进入下一个循环....

2.requests模块

requests库

get 方法 -------直接从服务器那里获得资源。
post方法 --------修改服务器上的资源。大多是提交表单或许上传文件,数据包含在请求体中
put方法 ----------从客户端想服务器发送数据并取代指定服务器上的内容
delete 方法 ------------请求服务器删除指定页面
connect 方法 ----------当服务器为跳板,让服务器代替客户端访问其他网页
options 方法 -----------允许客户端查看服务器的性能
trace方法 -------------回显服务器收到的请求,主要用于测试


发送get,post请求
response = requests.get(url)
response = requests.post(url,data={请求体的字典})


response的方法
response.text
该方法经常会出现乱码,出现乱码使用response.encoding=”utf-8”


response.content.decode()
把响应的二进制字节流转化为str类型

3.实例代码

扫描二维码关注公众号,回复: 7801653 查看本文章
#以前程无忧网为例
import requests
from bs4 import BeautifulSoup
total = []
for i in range(1, 2):#爬取页数,可自行修改
    url = 'http://search.51job.com/list/070000%252C020000,000000,0000,00,9,99,Python,2,{}.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=1&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='.format(
        i)
    res = requests.get(url)
    res.encoding = 'gbk'
    soup = BeautifulSoup(res.text, 'html.parser')
    posts = soup.select('#resultList > div > p > span > a')
    # print(posts)
    post1 = list(map(lambda x: x.text.strip(), posts))
    # print(post1)#获取职位名称
    moneys = soup.select('#resultList > div > span.t4')
    money1 = list(map(lambda x: x.text.strip(), moneys))
    # print(moneys)#获取薪水
    for post, money in zip(post1, money1):
        total.append({'post': post, 'money': money})  # 打包成字典
print(total)

运行结果:(由于不会排版字典,所以结果很乱)

 4.需要注意的地方

需要指令安装函数库requests库,注意不要安装错误。pycharm用户可直接在软件内搜索安装,sublime需在控制台输入pip install requests指令安装

猜你喜欢

转载自www.cnblogs.com/yezishen/p/11823537.html
今日推荐