urllib.request: POST 数据应该是字节、字节的可迭代对象或文件对象
urllib.request: POST data should be bytes, an iterable of bytes, or a file object
我需要访问 HTML 网站并在该网站上搜索图像。它可能不是那么漂亮,但我可以访问该网站,我只需要一些关于搜索 IMG 的最佳方式的指导。
我试图将其视为文件,但出现错误提示我需要将数据转换为字节。
告诉我你的想法。
from urllib import request
import re
website = request.urlopen('https://www.google.com', "rb")
html = website.read()
hand = html.decode("UTF-8")
for line in hand:
line = line.rstrip()
if re.search('^img', line):
print(line)
TypeError: POST data should be bytes, an iterable of bytes, or a file
object. It cannot be of type str
我希望得到一个 img 列表
It might not be that pretty, but I am able to access the website..
实际上,由于调用访问该网站的函数出错,您无法访问该网站。
你需要看看urllib.request.urlopen()
的函数签名。
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
在你的这行代码中:
website = request.urlopen('https://www.google.com', "rb")
... 字符串 'rb'
被解释为要在请求正文中发送的 data
参数。这是因为您提供了 2 个位置参数,其中 'rb'
是第二个,data
是函数签名中的第二个位置参数。
这是 data
允许的:
The supported object types include bytes, file-like objects, and iterables.
所以字符串 'rb'
不是这些类型中的任何一种。
但这里真正的问题是你在猜测如何使用这个函数。 open()
内置函数和 urllib.request.urlopen()
函数在操作方式上有很大不同,因此您需要阅读文档以了解如何正确使用它们。
此外,我建议除非您绝对必须使用 urllib
,否则请改用 requests
库。
functionurlopen
的签名是:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
在您的代码中,urlopen('https://www.google.com', "rb")
将 "rb" 字符串设置为 data
参数,而不是另一个函数 open
中的 mode
参数
我需要访问 HTML 网站并在该网站上搜索图像。它可能不是那么漂亮,但我可以访问该网站,我只需要一些关于搜索 IMG 的最佳方式的指导。
我试图将其视为文件,但出现错误提示我需要将数据转换为字节。
告诉我你的想法。
from urllib import request
import re
website = request.urlopen('https://www.google.com', "rb")
html = website.read()
hand = html.decode("UTF-8")
for line in hand:
line = line.rstrip()
if re.search('^img', line):
print(line)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str
我希望得到一个 img 列表
It might not be that pretty, but I am able to access the website..
实际上,由于调用访问该网站的函数出错,您无法访问该网站。
你需要看看urllib.request.urlopen()
的函数签名。
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
在你的这行代码中:
website = request.urlopen('https://www.google.com', "rb")
... 字符串 'rb'
被解释为要在请求正文中发送的 data
参数。这是因为您提供了 2 个位置参数,其中 'rb'
是第二个,data
是函数签名中的第二个位置参数。
这是 data
允许的:
The supported object types include bytes, file-like objects, and iterables.
所以字符串 'rb'
不是这些类型中的任何一种。
但这里真正的问题是你在猜测如何使用这个函数。 open()
内置函数和 urllib.request.urlopen()
函数在操作方式上有很大不同,因此您需要阅读文档以了解如何正确使用它们。
此外,我建议除非您绝对必须使用 urllib
,否则请改用 requests
库。
functionurlopen
的签名是:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
在您的代码中,urlopen('https://www.google.com', "rb")
将 "rb" 字符串设置为 data
参数,而不是另一个函数 open
中的 mode
参数