从python中的txt文件打开链接

时间:2016-06-24 20:56:35

标签: python beautifulsoup urllib2 urllib

我想请求rss程序的帮助。我正在做的是收集包含我项目相关信息的网站,而不是检查他们是否有RSS订阅源。 链接存储在txt文件中(每行一个链接)。 所以我有一个带有基本URL的txt文件,需要检查rss。

我发现这段代码可以让我的工作变得更轻松。

import requests  
from bs4 import BeautifulSoup  

def get_rss_feed(website_url):
    if website_url is None:
        print("URL should not be null")
    else:
        source_code = requests.get(website_url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.find_all("link", {"type" : "application/rss+xml"}):
            href = link.get('href')
            print("RSS feed for " + website_url + "is -->" + str(href))

get_rss_feed("http://www.extremetech.com/")

但我想从txt文件中打开我收集的网址,而不是逐个打字。

所以我试着用这个来扩展程序:

from bs4 import BeautifulSoup, SoupStrainer

with open('test.txt','r') as f:
    for link in BeautifulSoup(f.read(), parse_only=SoupStrainer('a')): 
        if link.has_attr('http'): 
            print(link['http'])

但是这会返回错误,说beautifoulsoup不是http客户端。

我也延伸了这个:

def open()
    f = open("file.txt")
    lines = f.readlines()
    return lines

但这给了我一个用","

分隔的列表

如果有人能够帮助我,我真的很感激

2 个答案:

答案 0 :(得分:1)

通常你会这样做:

with open('links.txt', 'r') as f:
    for line in f:
        get_rss_feed(line)

此外,定义名为open的函数是个坏主意,除非您打算替换内置函数open

答案 1 :(得分:0)

我想你可以使用urllib

来实现
    import urllib
    f = open('test.txt','r')
    #considering each url in a new line...
    while True:
     URL = f.readline()
     if not URL:
       break
     mycontent=urllib.urlopen(URL).read()