在Python的requests庫中進行請求頭設置非常簡單。首先,確保已經安裝了requests庫。如果沒有安裝,可以使用以下命令進行安裝:
pip install requests
接下來,你可以使用以下代碼示例來設置請求頭:
import requests
url = 'https://example.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'Cookie': 'your_cookie_here',
}
response = requests.get(url, headers=headers)
print(response.text)
在這個示例中,我們設置了一些常見的請求頭,如User-Agent、Accept、Accept-Language等。你可以根據需要添加或修改這些請求頭。將your_cookie_here
替換為實際的cookie值(如果有的話)。最后,我們使用requests.get()
方法發送請求并打印響應內容。