Python 2.7 从html文本链接到python 2中的txt文件

Python 2.7 从html文本链接到python 2中的txt文件,python-2.7,Python 2.7,我只需要用python 2编写脚本的帮助,该脚本将获取本页的标题:,并将其逐行保存在文本文件中,如下所示: "Trump, Macron gloss over differences in France after rough start Trump spars with Macron as Air Force One lands in France Opinion: Which President Trump will show up in Paris? Two leaders holdin

我只需要用python 2编写脚本的帮助,该脚本将获取本页的标题:,并将其逐行保存在文本文件中,如下所示:

"Trump, Macron gloss over differences in France after rough start 
Trump spars with Macron as Air Force One lands in France
Opinion: Which President Trump will show up in Paris?
Two leaders holding bilateral talks"
...

请留下你的任何建议。多谢各位

您可以使用beautifulSoup来完成这项工作

from bs4 import BeautifulSoup

import requests

url = "https://lite.cnn.com/en"
r  = requests.get(url)

data = r.text
#different parsers : "lxml", "html5lib", "xml" and "html.parser"
soup = BeautifulSoup(data,"html.parser")
file = open('testfile.txt','a')
#loop thru our links
for link in soup.select('li a'):
    file.write(link.text + "\n")
file.close()
testfile.txt
有一些简单的方法我可以阅读HTML,但它可以阅读页面的源代码:

import urllib2
for line in urllib2.urlopen("https://lite.cnn.com/en"):
    file = open('testfile.txt','a')
    file.write(line)
    file.close()

为什么不使用?非常感谢您的评论,使用soup对我来说是个问题。我对lxml解析器有问题。您可以在bs构造函数中指定除
lxml
之外的其他解析器。检查更新的应答我得到的输出有错误:UserWarning:没有明确指定解析器,因此我正在使用此系统中可用的最佳HTML解析器(“lxml”)。这通常不是问题,但如果您在另一个系统上或在不同的虚拟环境中运行此代码,它可能会使用不同的解析器并表现出不同的行为。导致此警告的代码位于文件news.py的第15行。若要消除此警告,请传递附加参数'features=“lxml“'到美化组构造函数。这个输出给了我什么,我希望得到明文输出,它将被espack读取,稍后尝试默认的python内置解析器
html.parser
soup=beautifulsou(data,“html.parser”)
好的,它的工作错误消失了,现在下一个问题是我如何从这个普通文本中得到它?我收到错误:UnicodeEncodeError:“ascii”编解码器无法对位置4中的字符u'\xf1'进行编码:序号不在范围内(128)
import urllib2
for line in urllib2.urlopen("https://lite.cnn.com/en"):
    file = open('testfile.txt','a')
    file.write(line)
    file.close()