首页 > 解决方案 > python urllib,返回特定url的空页面

问题描述

我在使用 urllib 的特定链接时遇到问题。下面是我使用的代码示例:

from urllib.request import Request, urlopen
import re

url = ""
req = Request(url)
html_page = urlopen(req).read()

print(len(html_page))

这是我从两个链接得到的结果:

url = "https://www.dafont.com"
Length: 0

url = "https://www.stackoverflow.com"
Length: 196673

有人知道为什么会这样吗?

标签: pythonurllib

解决方案


尝试使用。你会得到回应。某些网站是安全的,仅响应某些用户代理。

from urllib.request import Request, urlopen

url = "https://www.dafont.com"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"}
req = Request(url, headers=headers)
html_page = urlopen(req).read()

print(len(html_page))

推荐阅读