zoukankan      html  css  js  c++  java
  • Python爬虫实例(2)

    普通的爬虫发送给服务器端的信息只有对于该页面的访问请求。,但是服务器并不知道发送这个请求使用的浏览器,操作系统,硬件平台等信息,

    而缺失这些信息的请求往往都是非正常的访问,例如爬虫.

    有些网站为了防止这种非正常的访问,会验证请求信息中的UserAgent(它的信息包括硬件平台、系统软件、应用软件和用户个人偏好),

    如果UserAgent存在异常或者是不存在,那么这次请求将会被拒绝(如上错误信息所示)

    所以可以尝试在请求中加入UserAgent的信息

    import requests
    from bs4 import BeautifulSoup
    url='https://www.zhihu.com/explore'
    ua={'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    soup=BeautifulSoup(requests.get(url,headers=ua).text,'html.parser')
    for link in soup.find_all('a',class_='ExploreSpecialCard-title'):
    print(link.text)
    登录才有数据
    般有三种解决办法,
    一是requests模拟登录,但是会有参数加密的问题和验证码的问题,有点难;
    二是selenium模拟登录,要解决验证码的问题;
    三是手动登录后获取cookie,在requests中加入cookie,这种方法比较简单,但是受cookie有效期的限制,要经常更换cookie。

    import requests
    headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    ,'cookie':'PHPSESSID=6puau1maqec5np1k7mi4pl3f82; gznotes-visited=true'}
    session=requests.Session()
    response=session.get('http://test.zhonghuajinfu.com/zhjfad/cms/index',headers=headers)
    print(response.text)
     
  • 相关阅读:
    hibernate--could not initialize proxy
    20160509-hibernate--继承映射
    CF1111C Creative Snap
    CF1097D Makoto and a Blackboard
    CF1091D New Year and the Permutation Concatenation
    CF1096D Easy Problem
    CF1076E Vasya and a Tree
    CF1081C Colorful Bricks
    CF1081E Missing Numbers
    CF1093D Beautiful Graph
  • 原文地址:https://www.cnblogs.com/cyq0528/p/12752390.html
Copyright © 2011-2022 走看看