【问题标题】:Open links from txt file in python在python中打开txt文件的链接
【发布时间】:2016-06-24 20:56:34
【问题描述】:

我想就 rss 程序寻求帮助。我正在做的是收集包含我项目相关信息的网站,然后检查它们是否有 rss 提要。 链接存储在 txt 文件中(每行一个链接)。 所以我有一个 txt 文件,其中包含需要检查 rss 的基本 url。

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

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 文件中打开我收集的 url,而不是一个一个地输入。

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

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

但这给了我一个用“,”分隔的列表

如果有人能帮助我,我将非常感激

【问题讨论】:

    标签: python beautifulsoup urllib2 urllib


    【解决方案1】:

    通常你会这样做:

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

    此外,除非您打算替换内置函数 open,否则使用名称 open 定义函数是一个坏主意。

    【讨论】:

    • 谢谢我试一试。感谢 open 的建议,我错过了
    • 我已将您建议的代码插入到程序中。现在它返回没有任何错误消息,但也没有结果。 root@loko:~# sudo python /root/Desktop/rsskeres.py root@loko:~# sudo python /root/Desktop/rsskeres.py 如果我从你的代码中打印出行,我会得到 url root@loko:~# sudo python /root/Desktop/nyit3.py theguardian.com 这是原始程序给出的返回:root@loko:~# sudo python /root/Desktop/rsskeres.py theguardian.com/is 的 RSS 提要 --> @ 987654323@可能是什么问题?
    • 我想你会想要line.rstrip()
    【解决方案2】:

    我想你可以通过使用 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()
    

    【讨论】:

    猜你喜欢
    • 2019-07-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多