我可以在 Python 中使用 os.path.join() 连接 url 还是有更好的方法?



我需要导航到不同的网址才能从每个网址下载图像。 网址是连续的,所以我认为最好手动创建它们,而不是在每个页面中使用"下一步"按钮。 我正在尝试生成 url 的不同部分,然后将它们与 os.path.join(( 连接在一起。

这是我的工作代码:

starting_url = 'https://www.mangareader.net/one-piece'
storing_folder = '/Users/macbook/Documents/Media/Fumetti/One_Piece'
ch_numb_regex = re.compile(r'd+')
for chapter in os.listdir(storing_folder):
if not chapter.startswith('.'):
if os.listdir(os.path.join(storing_folder, chapter)) == []:
continue
else:
try:
page = 1
while True:
res = requests.get(os.path.join(starting_url, str(ch_numb_regex.search(chapter).group()) ,str(page)))
res.raise_for_status()
manga_soup = bs4.BeautifulSoup(res.text, 'lxml')
manga_image = manga_soup.select('#imgholder img')
manga_url = manga_image[0].get('src')
res = requests.get(manga_url)
res.raise_for_status()
imageFile = open(os.path.join(storing_folder, chapter, page), 'wb')
imageFile.write()
imageFile.close()
page += 1
except requests.HTTPError:
continue

但是,我收到错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-20-1ee22580435e> in <module>()
7 res = requests.get(manga_url)
8 res.raise_for_status()
----> 9 imageFile = open(os.path.join(storing_folder, chapter, page), 'wb')
10 imageFile.write()
11 imageFile.close()
/anaconda3/lib/python3.6/posixpath.py in join(a, *p)
90                 path += sep + b
91     except (TypeError, AttributeError, BytesWarning):
---> 92         genericpath._check_arg_types('join', a, *p)
93         raise
94     return path
/anaconda3/lib/python3.6/genericpath.py in _check_arg_types(funcname, *args)
147         else:
148             raise TypeError('%s() argument must be str or bytes, not %r' %
--> 149                             (funcname, s.__class__.__name__)) from None
150     if hasstr and hasbytes:
151         raise TypeError("Can't mix strings and bytes in path components") from None
TypeError: join() argument must be str or bytes, not 'int'

但它们都应该是字符串。

我可以在 Python 中使用os.path.join()来连接网址吗 [...]?

不是便携式,不是。对于非 Unix 操作系统,路径分隔符将不会'/',因此您将创建格式错误的 URI。

有没有更好的方法?

是的。你可以使用 urllib。

最新更新