Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—如何循环遍历URL的文本文件并将所有URL传递到重定向处理程序中_Python - Fatal编程技术网

Python—如何循环遍历URL的文本文件并将所有URL传递到重定向处理程序中

Python—如何循环遍历URL的文本文件并将所有URL传递到重定向处理程序中,python,Python,我最近使用Python的BeautifulSoup库收集了一堆元数据。我将元数据中包含的所有URL保存到一个.txt文件中。但是,我需要所有重定向URL。我可以通过以下方式一次创建一个url: def get_redirect_url(url): opener = urllib2.build_opener(urllib2.HTTPRedirectHandler) request = opener.open(url) return request.url print ge

我最近使用Python的BeautifulSoup库收集了一堆元数据。我将元数据中包含的所有URL保存到一个.txt文件中。但是,我需要所有重定向URL。我可以通过以下方式一次创建一个url:

def get_redirect_url(url):
    opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
    request = opener.open(url)
    return request.url 
print get_redirect_url("www.foo.com")
print ""
我试图将文本文件传递到一个列表中,然后将该列表作为参数传递,结果出现以下错误:“TypeError:get\u redirect\u url()正好接受一个参数(给定11个)”


是否有一种方法可以将文本文件或该文本文件中数据的列表表示形式作为函数的参数传递、循环文件并提取所有重定向URL?谢谢大家。

我想你们打错了
get\u redirect\u url()

# UNTESTED
def get_lots_of_urls(filename):
    with open(filename) as infile:
        return [get_redirect_url(url.strip()) for url in infile]

for redirect_url in get_lots_of_urls('input_file.txt'):
    print redirct_url
*
是“splat”运算符:它将列表作为输入,并将其展开为函数调用中的实际位置参数

因此,通过编写
get\u redirect\u url(*data)
您说的是
get\u redirect\u url(url1,url2,url3,…)
。但是,函数只接受一个参数:url

总而言之,一次只能用一个参数调用
get\u redirect\u url()

def get_redirect_url(url):
    opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
    request = opener.open(url)
    return request.url 


with open ('openCRS_url.txt', 'r') as myFile:
    urls = [line.strip() for line in myFile]
    redirect_urls = [get_redirect_url(url) for url in urls]
    print redirect_urls

你能用BeatifulSoup刮东西,但不能循环浏览文件?是您想要的模块。您可能需要将其剥离。
def get_redirect_url(url):
    opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
    request = opener.open(url)
    return request.url 


with open ('openCRS_url.txt', 'r') as myFile:
    urls = [line.strip() for line in myFile]
    redirect_urls = [get_redirect_url(url) for url in urls]
    print redirect_urls