【问题标题】:python add http:// to url open sys argspython将http://添加到url open sys args
【发布时间】:2016-02-20 18:34:34
【问题描述】:

对 python 来说非常新,我正在尝试接受一个命令行参数,它是一个网站并将其设置为一个变量。我使用下面的行来执行此操作。

sitefile = ur.urlopen(sys.argv[1])

问题是它只有在命令行中完美格式化为“python filename.py http://mywebsite.com/contacts.html”时才有效。我希望能够删除 http://。我尝试了以下两种方法:

sitefile = ur.urlopen(sys.argv[1].startswith('http://'))

得到错误信息:AttributeError: 'bool' object has no attribute 'timeout'

sitefile = 'http://' + (ur.urlopen(sys.argv[1]))

收到错误消息:ValueError:未知 url 类型:'mywebsite.com/contacts.html'。它似乎只是忽略了这个 concat 的前半部分。

【问题讨论】:

  • 阅读文档,startswith 不会像你想的那样做:sitefile = ur.urlopen('http://' + sys.argv[1])
  • startswith() 如果字符串以 arg 开头,则返回布尔值,而不是您要查找的内容。您需要在传递给ur.urlopen() 之前添加'http://。试试ur.urlopen('http://' + sys.argv[1])
  • 非常感谢!

标签: python sys urlopen


【解决方案1】:

你是什么?给出完整的代码。

sys.argv[1].startswith('http://') 返回一个 bool 对象,去掉 http:// 应该使用 sys.argv[1].replace('http://', '')

我认为代码应该像以下几行:

#!/usr/bin/env python
# encoding: utf-8
import sys
import urllib2

if len(sys.argv) != 2:
    print('usage: {} <url>'.format(sys.argv[0]))
    sys.exit()
url = sys.argv[1]

req = urllib2.urlopen(url)
print(req.read())

【讨论】:

  • ur 设置为 import urllib.request 它似乎是一个简单的 concat 语法错误,因为以前的 cmets 解决了我的问题
猜你喜欢
  • 2019-06-08
  • 2014-11-03
  • 1970-01-01
  • 2012-08-15
  • 2011-11-28
  • 2020-06-23
  • 1970-01-01
  • 2011-09-08
相关资源
最近更新 更多