美文网首页
Python-数据爬取

Python-数据爬取

作者: 柳清檀 | 来源:发表于2019-07-16 05:41 被阅读0次

数据购买

数据公司
数据交易所

爬取数据

数据获取
数据清洗
第三方框架:scrapy、scrapy-redis
反爬虫- 反反爬虫

网络部分

HTTP协议
HTTPS

网络爬虫

爬取数据的原理:使用程序批量获取数据-->用程序模拟一个浏览器,发送HTTP请求(GET、POST)
HTTP原理:(BS结构)
客户端请求 -- 服务器响应

url

protocol hostname post path
e.g
https://www.baidu.com/s?ie=UTF-8&wd=scrapy%E6%A1%86%E6%9E%B6
url?参数:【ie=UTF-8&wd=scrapy%E6%A1%86%E6%9E%B6】
ie 参数名、UTF-8参数值(两者间由=分割,不同的参数间由&分割)
注:%E6%A1%86%E6%9E%B6对中文的加密转码
中文编码、解码工具

  • request
    相当于发送一个字符串(带格式的)
    请求行、请求头、空行、数据
  • post

方式由服务器决定:
若http协议中包含数据部分,那么请求方式为post【对数据要求较高的情况下】
url后面参数 - get方式提交(无请求体)
(爬虫为方便不适用accept encoding,直接使用明文传递)

响应:
状态行、消息报头、空行、响应正文
状态(e.g.200正常、404)

import urllib.request
import urllib.parse#只能加密字典
kw = {
    "kw":"北京航空航天大学"
}
url = "http://tieba.baidu.com/f?"
url += urllib.parse.urlencode(kw)
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
with open("demo1.html","a",encoding = "utf-8") as f:
    f.write(content)
import urllib.request
import urllib.parse#只能加密字典
keyword = input("请输入贴吧名")
kw = {
    "kw":keyword
}
startIndex = int(input("起始页"))
endIndex = int(input("结束页"))
url = "http://tieba.baidu.com/f?"
url += urllib.parse.urlencode(kw)
for index in range(startIndex, endIndex+1):
    pn = str((index-1)*50)
    url += "&pn="+ pn
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    content = response.read().decode("utf-8")
    with open(f"E:\py\demo{index}.html","a",encoding = "utf-8") as f:
        f.write(content)

xml--xpath


image.png image.png

属性过滤:

  • id
    xpath正确但python中不返回正确内容:反爬虫
    可能是js生成

相关文章

网友评论

      本文标题:Python-数据爬取

      本文链接:https://www.haomeiwen.com/subject/ilojhctx.html