簡體   English   中英

嘗試從 Python 中的一系列 URL 下載數據(文本)

[英]Trying to download data (text) from a range of URLs in Python

抱歉這個可能很無聊的問題。 我正在嘗試使用 Python 從一系列 URL 中一次性下載文本。 它們遵循一個非常簡單的結構:

" http://example.com/01000/01000/01000.htm "; " http://example.com/01000/01001/01001.htm ";

依此類推,直到 01099。

獲取文本后,我需要使用 nltk 工具包對其進行分析。 我曾嘗試在 Windows 上使用 wget,但在命令行中不起作用。 我想知道是否有一種方法,類似於用於 URL 的 glob 模塊,可以一次性從此范圍下載數據。

(范圍內還有一些空白 URL。)

非常感謝你的幫助。

一旦您使用字符串操作獲得了 URL(看到您知道 URL 的結構),您就可以使用Requests 模塊

例子;

import requests

base_url = "http://example.com/01000/01001/0"
for i in range(1000, 1100):
    target_url = base_url + str(i) + ".htm"
    r = requests.get(target_url)

    print(r.text) # python 3 only

你可以試試我的python3-wget 模塊 這是一個使用示例;

#!/usr/bin/python3
#-*- coding:utf-8 -*-

import wget

urls = 'http://example.com/01000/01000/0'
for x in range(1000, 1099):
    url = urls + str(x) + '.htm' 
    filename = wget.download(url)

這將下載所有文件,如果您需要從頁面中提取特定文本,您將需要考慮使用 Requests 和 BeautifulSoup4 創建一個簡單的網絡抓取工具。

非常感謝你的幫助。 最后,這就是我的代碼的樣子:

import requests
base_url = "http://example.com/01000/0"
for i in range(1000, 1100):
    target_url = base_url + str(i) + '/' + '0' + str(i) + ('.htm')
    r = requests.get(target_url)
    print(target_url)

    with open(str(i) + ".htm", 'w', encoding="iso-8859-1") as f:
    f.write(r.text)

 #The encoding is due to language specific text. 
#It downloaded all the files in the given range: http://example.com/01000/01000/01000.htm 
#to /01000/01099/01099.htm.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM