【问题标题】:Copy and paste text from webpage to txt file or csv file将网页中的文本复制并粘贴到 txt 文件或 csv 文件
【发布时间】:2018-12-18 22:43:33
【问题描述】:

我正在尝试从网页复制文本并将其粘贴到文本文件中。没什么太花哨的,但我似乎无法弄清楚如何去做或在网上找到任何有效的东西。

import requests

url = 'https://seekingalpha.com/article/4166013-t-t-q1-2018-results-earnings-call-transcript?part=single'
data = requests.get(url)

with open('file.txt','w') as out_f:
   out_f.write(data.text)

我收到一个 unicode 编码错误,\ufeff。有没有办法只选择全部,复制,然后粘贴到文本文件中?看起来很简单,但无法弄清楚。

提前感谢您!

【问题讨论】:

    标签: python web-scraping error-handling


    【解决方案1】:

    尝试将您的文本编码为 utf-8

    import requests
    
    url = 'https://seekingalpha.com/article/4166013-t-t-q1-2018-results-earnings-call-transcript?part=single'
    data = requests.get(url)
    
    with open('file.txt','w') as out_f:
       out_f.write(data.text.encode('utf-8'))
    

    【讨论】:

    • 谢谢!那成功了。我不得不将 data.text.encode 放在 str() 中,因为它说 write() 参数必须是 str 而不是字节,否则解决了问题!跟进,我拉的文本有很多 HTML。我还是相当新的@python,但是通过一些快速的谷歌搜索,我应该使用 BeautifulSoup 来解析文本?
    • BeautifulSoup 不是 HTML 解析器,它适用于一些 python html 解析库。这是一个 html dom 实用程序。如果你想使用 html 是最快最简单的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2020-02-16
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多