【问题标题】:urllib.error.HTTPError: HTTP Error 404: Not Found even though I can go to the link?urllib.error.HTTPError:HTTP 错误 404:即使我可以转到链接,也找不到?
【发布时间】:2022-10-14 16:11:13
【问题描述】:
import requests
from bs4 import BeautifulSoup
import wget   # Downloads files from url

page = requests.get("https://en.wikipedia.org/wiki/Gallery_of_sovereign_state_flags")
soup = BeautifulSoup(page.content, 'html.parser')

for flag in soup.find_all('a', attrs={'class': "image"}):
    src = flag.contents[0]['src']
    src = src.replace("thumb/", "")
    src = "https:" + src
    sep = '.svg'
    fixed_src = src.split(sep, 1)[0] + ".svg"
    print(fixed_src)
    for country in data["Country"]:    # A column containing country names
        if country in fixed_src:
            wget.download(fixed_src, f'flags/{country}.svg')

它适用于大多数生成的 url,但一旦到达“澳大利亚”,它就会返回 urllib.error.HTTPError: HTTP Error 404: Not Found。但是当我按下链接时,它会将我重定向到它并找到它。

我尝试放置一个 if 语句来忽略澳大利亚,但很少有其他 url 返回相同的错误。

有任何想法吗?

【问题讨论】:

    标签: python beautifulsoup python-requests-html


    【解决方案1】:

    我认为您的问题很可能与您的网址中的转义字符有关。浏览器知道如何解决它们;但是似乎 wget 库不知道该怎么做,您必须自己摆脱转义字符。

    在执行 wget 之前尝试将 urllib.parse.unquote(fixed_src) 添加到您的代码中。至少对我来说,它解决了 404 的问题。

    看到不同:

    在取消引用之前:

    https://upload.wikimedia.org/wikipedia/commons/7/7a/Flag_of_Afghanistan_%282004%E2%80%932021%29.svg
    

    取消引用后:

    https://upload.wikimedia.org/wikipedia/commons/7/7a/Flag_of_Afghanistan_(2004–2021).svg
    

    完整代码如下:

    import urllib
    import requests
    from bs4 import BeautifulSoup
    import wget   # Downloads files from url
    
    page = requests.get("https://en.wikipedia.org/wiki/Gallery_of_sovereign_state_flags")
    soup = BeautifulSoup(page.content, 'html.parser')
    
    for flag in soup.find_all('a', attrs={'class': "image"}):
        src = flag.contents[0]['src']
        src = src.replace("thumb/", "")
        src = "https:" + src
        sep = '.svg'
        fixed_src = src.split(sep, 1)[0] + ".svg"
        print(fixed_src)
        url_unquoted = urllib.parse.unquote(fixed_src)
        print(url_unquoted)
        for country in data["Country"]:    # A column containing country names
            if country in url_unquoted:
                wget.download(url_unquoted, f'flags/{country}.svg')
    

    Similar problem, found with "python wget fails for url" from Google

    urllib documentation here

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 2020-03-22
      • 2020-11-21
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      相关资源
      最近更新 更多