• requests入门


    1.通过GET请求获得搜索结果的网页源代码

    import requests
    
    name=input("请输入想要搜索的明星:")
    url=f'https://www.sogou.com/web?query={name}'
    header={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"
    }
    resp=requests.get(url,headers=header)#处理一个反爬
    print(resp)
    print(resp.text)#拿到页面源代码

    在爬取过程中,由于需要爬取的网站设置了反爬机制,所以需要通过“resp=requests.get(url,headers=header)”来处理反爬,在检查页面中找到Request Headers中的“User-Agent”模块,将其复制到headers字典集中。通过语句“resp=requests.get(url,headers=header)”引用。

     2.通过POST请求爬取百度翻译结果

    import requests
    
    url="https://fanyi.baidu.com/sug"
    s=input("请输入你要查询的单词:")
    header={
        "kw":s
    }
    #发送post请求,发送的数据必须放在字典中,通过data传递
    resp=requests.post(url,data=header)
    print(resp)
    print(resp.json())#将服务器返回的内容直接处理成json()

    在发送post请求时,发送的数据必须放在字典中,通过data传递。

     运行结果:

  • 相关阅读:
    bzoj 5455
    hdu 6705
    hdu 6706
    斜率优化
    bzoj3672
    bzoj1367
    bzoj2118
    bzoj2337
    Codeforces 1077D Cutting Out(二分答案)
    Codeforces 1079C Playing Piano(记忆化搜索)
  • 原文地址:https://www.cnblogs.com/zyj3955/p/15041041.html
Copyright © 2020-2023  润新知