找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4343|回复: 1

[求助] python 通过requests 爬取百度搜索页

1

主题

1

帖子

1

积分

贫民

积分
1
taotaogoudan 发表于 2017-8-22 23:32:37 | 显示全部楼层 |阅读模式
  1. #! python3
  2. import requests
  3. res = requests.get('https://www.baidu.com/s?wd=python')
  4. print(res.url)
  5. print(res.headers)
  6. print(res.content)
复制代码
爬取这个页面,出来一个莫名其妙的内容.不知道为什么. 代码怎么改?还需要设置什么吗? 多问一句requests.get里 为什么要设置headers,有什么用处.
新手一枚,多多指教

https://www.baidu.com/s?ie=utf-8 ... baidu&wd=python

{'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'Connection': 'Keep-Alive', 'Content-Length': '227', 'Content-Type': 'text/html', 'Date': 'Tue, 22 Aug 2017 15:14:52 GMT', 'Last-Modified': 'Tue, 08 Aug 2017 12:43:00 GMT', 'P3p': 'CP=" OTI DSP COR IVA OUR IND COM "', 'Pragma': 'no-cache', 'Server': 'BWS/1.1', 'Set-Cookie': 'BD_NOT_HTTPS=1; path=/; Max-Age=300, BIDUPSID=A5F6F7E3ABB0E804ED6D9899C959B3F9; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com, PSTM=1503414892; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com', 'Strict-Transport-Security': 'max-age=0', 'X-Ua-Compatible': 'IE=Edge,chrome=1'}


b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>'


红色的为返回的页面
回复

使用道具 举报

0

主题

5

帖子

5

积分

贫民

积分
5
liuvz11 发表于 2017-8-24 10:17:46 | 显示全部楼层
本帖最后由 liuvz11 于 2017-8-25 14:05 编辑
  1. # -*- coding: utf-8 -*-
  2. import requests

  3. url = "http://www.baidu.com/s?wd=python"
  4. headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36"}

  5. res = requests.get(url, headers=headers)
  6. print res.text
复制代码

加个UA, 还有, 不要用https, 麻烦
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表