簡體   English   中英

TypeError:urlopen()獲得了意外的關鍵字參數'headers'_Python3

[英]TypeError: urlopen() got an unexpected keyword argument 'headers'_Python3

我試圖抓取一個網站來使用Python 3.6.4進行練習,但是我不斷收到TypeError意外的關鍵字參數headers 有誰知道是什么原因引起的錯誤?

這是我的代碼:

 from urllib.request import Request, urlopen
 url = 'https://www.inside.com.tw'
 headers = {'User-Agent': 'Mozilla/5.0'}
 html = urlopen(url, headers=headers).read()

我得到的錯誤:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: urlopen() got an unexpected keyword argument 'headers'

urllib模塊與首選requests模塊的工作方式不太相同。
您可以在哪里使用requests

import requests
url = 'https://www.inside.com.tw'
headers = {'User-Agent': 'Mozilla/5.0'}
html = requests.get(url, headers=headers).content

使用urllib ,您需要創建一個Request對象,並向其中添加標頭:

from urllib.request import Request, urlopen
url = 'https://www.inside.com.tw'
headers = {'User-Agent': 'Mozilla/5.0'}
request = Request('https://www.inside.com.tw', headers=headers)
html = urlopen(request).read()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM