网页爬虫 - 用python的requests库爬虫时,post参数后却没有返回预期的结果
高洛峰
高洛峰 2017-04-18 09:41:09
[Python讨论组]

我使用的是python3.4,在用requests库爬虫时,向百度post了一个参数,但是返回来的内容却没有python关键词的搜索列表,这是什么原因呢?我的代码如下:

import requests
import urllib
from bs4 import BeautifulSoup

url = 'https://www.baidu.com/s?'
key_word={'key':'python'}
headers = {'User_Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}

def get_data(url):
    try:
        html=requests.post(url,data=key_word,headers=headers)
        if html.status_code == 200:
            soup=BeautifulSoup(html.text,'lxml')
            return soup
        else:
            print('error')
    except urllib.error.HTTPError as e:
        print(url, e, str(time.time()))

print(get_data(url))

以下是我返回的内容:







页面不存在_百度搜索



网页新闻贴吧知道音乐图片视频地图文库更多»

很抱歉,您要访问的页面不存在!

温馨提示:

  1. 请检查您访问的网址是否正确
  2. 如果您不能确认访问的网址,请浏览百度更多页面查看更多网址。
  3. 回到顶部重新发起搜索
  4. 如有任何意见或建议,请及时反馈给我们。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
高洛峰

POST不可以,用GET,请求这个URL http://www.baidu.com/s?wd=python

bash下可以这么测试:

curl http://www.baidu.com/s\?wd\=python > python.html

然后打开这个python.html看吧

天蓬老师

你是说百度的搜索提示列表,人家用的是get请求,不是post

>>> r=requests.get('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=pyth
on')
>>> r.text
'window.baidu.sug({q:"python",p:false,s:["python基础教程","python set","python j
son","python mysql","python web开发","python requests","python for循环","python3
","python环境变量设置","python 多线程"]});'

直接输入的url是https://www.baidu.com/baidu?word=python&ie=utf-8&tn=98012088_2_dg&ch=9
直接requests.get就行

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号