【问题标题】:Urllib bad request issueUrllib 错误请求问题
【发布时间】:2016-06-30 02:03:21
【问题描述】:

我尝试了here 中的每个'User-Agent',但我仍然得到urllib.error.HTTPError: HTTP Error 400: Bad Request。我也试过this,但我得到了urllib.error.URLError: File Not Found。我不知道该怎么做,我目前的代码是;

from bs4 import BeautifulSoup
import urllib.request,json,ast

with open ("urller.json") as f:
    cc = json.load(f) #the file I get links, you can try this link instead of this
    #cc = ../games/index.php?g_id=23521&game=0RBITALIS 

for x in ast.literal_eval(cc): #cc is a str(list) so I have to convert
    if x.startswith("../"):

        r = urllib.request.Request("http://www.game-debate.com{}".format(x[2::]),headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'})
        #x[2::] because I removed '../' parts from urlls

        rr = urllib.request.urlopen(r).read()
        soup = BeautifulSoup(rr)

        for y in soup.find_all("ul",attrs={'class':['devDefSysReqList']}):
            print (y.text)

编辑:如果您只尝试 1 个链接,它可能不会显示任何错误,因为我每次在第 6 个链接时都会收到错误。

【问题讨论】:

  • 使用urllib吗?我刚试过requests.get("http://www.game-debate.com/games/index.php?g_id=23521&game=0RBITALIS"),效果很好。 requests 几乎在各个方面都远超。
  • @AkshatMahajan 但我编辑了这个问题,如果你只尝试 1 个链接可能会没问题,因为我每次在 json 文件的第 6 个链接处都会收到错误的请求错误
  • 在发出请求之前,您是否尝试过打印每个 URL?也许该 URL 以某种明显的方式格式不正确。
  • @JohnGordon 我收到错误的链接是../games/index.php?g_id=23255&game=12 Labours of Hercules II: The Cretan Bull
  • 那些嵌入的空格可能会导致问题。我不认为 URL 中允许使用文字空格。

标签: python beautifulsoup python-3.4 urllib bad-request


【解决方案1】:

快速解决方法是将空格替换为+

url = "http://www.game-debate.com"
r = urllib.request.Request(url + x[2:] ,headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'})

更好的选择可能是让 urllib quote 参数:

from bs4 import BeautifulSoup
import urllib.request,json,ast
from urllib.parse import quote, urljoin

with open ("urller.json") as f:
    cc = json.load(f) #the file I get links, you can try this link instead of this
    url = "http://www.game-debate.com"


    for x in ast.literal_eval(cc):  # cc is a str(list) so I have to convert
        if x.startswith("../"):
            r = urllib.request.Request(urljoin(url, quote(x.lstrip("."))), headers={
                'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'})

            rr = urllib.request.urlopen(r).read()
            soup = BeautifulSoup(rr)
            print(rr.decode("utf-8"))

            for y in soup.find_all("ul", attrs={'class':['devDefSysReqList']}):
                print (y.text)

url 中的空格无效,需要百分比编码为%20 或替换为+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多