【问题标题】:when navigating to an url, I'm getting error: "urlopen() got an unexpected keyword argument 'headers' "导航到 url 时,出现错误:“urlopen() got an unexpected keyword argument 'headers'”
【发布时间】:2021-12-25 15:58:07
【问题描述】:

我正在尝试使用 urllib.request.urlopen 导航到特定网页。

hdr = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
my_url ='https://www.cms.co.il/catalog/products.aspx?keySearch=9SX3000I'
weburl = urllib.request.urlopen(my_url,headers=hdr,timeout=30)

我收到一个错误:urlopen() got an unexpected keyword argument 'headers'

我尝试删除标题,但随后出现错误:HTTP Error 403: Forbidden

如何在不出错的情况下访问此页面?

【问题讨论】:

    标签: python python-3.x http-headers web-crawler urllib


    【解决方案1】:

    urllib.request.urlopen 不接受 headers 参数,但 urllib.request.Request 接受。您还需要指定标题键,例如'User-Agent' 在这种情况下。

    from urllib.request import urlopen, Request
    
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
    my_url ='https://www.cms.co.il/catalog/products.aspx?keySearch=9SX3000I'
    
    response = urlopen(Request(my_url,headers=headers),timeout=30)
    
    print(response.status)
    > 200
    html = response.read()
    print(html[:20])
    > b"\n<!DOCTYPE html>\n<html>\n<head>\n<title>CMS Compucenter Ltd</title>\n\n<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\r\nnew Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagNam"
    

    【讨论】:

    • @D Malan - 太棒了!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2022-12-02
    • 2014-09-24
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多