requests.gPython 用requests.get获取网页内容为空 ’ ’问题

来自:网络
时间:2022-01-09
阅读:
目录

下面先来看一个例子:

import  requests
result=requests.get("http://data.10jqka.com.cn/financial/yjyg/")
result

输出结果:

requests.gPython 用requests.get获取网页内容为空 ’ ’问题

表示成功处理了请求,一般情况下都是返回此状态码; 报200代表没问题

requests.gPython 用requests.get获取网页内容为空 ’ ’问题

 继续运行,发现返回空值,在请求网页爬取的时候,输出的text信息中会出现抱歉,无法访问等字眼,这就是禁止爬取,需要通过反爬机制去解决这个问题。headers是解决requests请求反爬的方法之一,相当于我们进去这个网页的服务器本身,假装自己本身在爬取数据。对反爬虫网页,可以设置一些headers信息,模拟成浏览器取访问网站 。

一、如何设置headers

拿两个常用的浏览器举例:

1、QQ浏览器

界面 F12 

requests.gPython 用requests.get获取网页内容为空 ’ ’问题

 点击network 键入 CTRL+R

requests.gPython 用requests.get获取网页内容为空 ’ ’问题

 单击第一个 最下边就是我门需要的 把他设置成headers解决问题

2、Miscrosft edge

二、微软自带浏览器

同样 F12 打开开发者工具

requests.gPython 用requests.get获取网页内容为空 ’ ’问题

 点击网络,CTRL+R

requests.gPython 用requests.get获取网页内容为空 ’ ’问题

 前文代码修改:

import requests
ur="http://data.10jqka.com.cn/financial/yjyg/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3880.400 QQBrowser/10.8.4554.400 '}
result = requests.get(ur, headers=headers)
result.text

成功解决不能爬取问题

返回顶部
顶部