簡體   English   中英

得到“ <Response [403]> ”在Python中使用request.post

[英]Get “<Response [403]>” using request.post in Python

我試圖從網站上獲取搜索結果,但是收到“ Response [403]”消息,我發現通過向header.post添加標頭來解決類似的403錯誤,但是對我的問題不起作用。 我應該怎么做才能正確獲得想要的結果?

from urllib.request import urlopen
import urllib.parse
import urllib.request
import requests
from bs4 import BeautifulSoup 

url="https://www.metal-archives.com/"
html= urlopen(url)
print("The keyword you entered to search is: %s\n" % 'Bathory')
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
result=requests.post(url, data='Bathory', headers=headers)
print(result.content)

首先,您不需要標題,因為您看到的是狀態碼200

>>> r = requests.get('https://www.metal-archives.com')
>>> r.status_code
200

如果您想搜索任何內容,則可以看到網址更改為

https://www.metal-archives.com/search?searchString=bathory

這意味着,您可以使用以下命令直接設置其格式:

>>> keyword = 'bathory'
>>> r = requests.get('https://www.metal-archives.com/search?searchString='+keyword)
>>> r.status_code
200
>>> 'bathory' in r.text
True

如果您檢查HTML,您會發現該form方法是GET(可能是導致403錯誤的原因):

<form id="search_form" action="https://www.metal-archives.com/search" method="get">

因此,您只需要構建搜索URL:

#Music genre search
result=requests.get( "https://www.metal-archives.com/search?searchString={0}&type=band_genre".format("Bathory") )
#Band name search
result=requests.get( "https://www.metal-archives.com/search?searchString={0}&type=band_name".format("Bathory") )

暫無
暫無

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

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