Python urlopen 返回值

标签 python python-2.7 urllib

我尝试将现有 URL 作为参数传递,以将其 HTML 加载到单个 txt 文件中:

for line in open('C:\Users\me\Desktop\URLS-HERE.txt'):
 if line.startswith('http') and line.endswith('html\n') :
    fichier = open("C:\Users\me\Desktop\other.txt", "a")
    allhtml = urllib.urlopen(line)
    fichier.write(allhtml)
    fichier.close()

但我收到以下错误:

TypeError: expected a character buffer object

最佳答案

urllib.urlopen() 返回的值是一个类似文件的对象,一旦打开它,就应该使用 read() 方法读取它,如下所示如以下代码片段所示:

for line in open('C:\Users\me\Desktop\URLS-HERE.txt'):
   if line.startswith('http') and line.endswith('html\n') :
      fichier = open("C:\Users\me\Desktop\other.txt", "a")
      allhtml = urllib.urlopen(line)
      fichier.write(allhtml.read())
      fichier.close()

希望这有帮助!

关于Python urlopen 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12017358/

相关文章:

python - 从传入数据点生成平滑曲线的算法

python - 将字符串解析为元组列表

python - 无法从 url 读取压缩文件

python - 尝试 POST 时出现 "getaddr info failed"错误

python - 为什么我的子列表包含所有元素?

python - 使用 numpy 数组计算函数返回 inf 和 nan

python - 在 QtCore.Qt.CrossPattern 上设置图案颜色和线条粗细

python - Odoo - 如何读取/获取另一个模块中的字段值

python - 如何自动选择和处理/root/facedetect 目录中的每个图像而不是选择特定图像

python - 用 Python 从许多 Google 搜索中抓取链接