【问题标题】:python- read txt to soup formatpython-将txt读取为汤格式
【发布时间】:2016-04-26 17:10:39
【问题描述】:

由于我无法打开我现在所在的 youtube 并且我想抓取我的 youtube 列表,我已经下载了 url 的内容:

from bs4 import BeautifulSoup
import urllib2


url='https://www.youtube.com/playlist?list=PLYjSYQBFeM-zQeZFpWeZ_4tnhc3GQWNj8'
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
f1 = open("c:/exp/soup.txt", "w")
f1.write(soup.prettify().encode('utf-8'))

首先,我无法阅读:

with open('C:/exp/soup.txt') as f:
    lines = f.readlines()
print lines

然后我不知道如何将其转换为汤文件:

f1 = open("C:/exp/soup.txt", "r")
f2=BeautifulSoup(f1)
type(f2)
print f2

我什么也没打印出来。

我需要再次将其转换为汤文件,以便继续解析该文件。

【问题讨论】:

  • 如果print lines 没有显示任何内容,那么您的文件为空

标签: python beautifulsoup


【解决方案1】:

您可以并且应该将类文件对象传递给BeautifulSoup 构造函数:

with open('C:/exp/soup.txt') as f:
   soup = BeautifulSoup(f, "html.parser")

print(soup)

如果您没有看到任何打印内容,则 C:/exp/soup.txt 文件为空。

【讨论】:

    【解决方案2】:

    这行得通:

    url='https://www.youtube.com/playlist?list=PLYjSYQBFeM-zQeZFpWeZ_4tnhc3GQWNj8'
    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    with urlopen(url) as link:
        result = link.read()
    soup = BeautifulSoup(result)
    f1 = open("E:/soup.txt", "wb")
    f1.write(soup.prettify().encode('utf-8'))
    

    从文件中读取:

    with open('E:/soup.txt','rb') as f:
        lines = f.readlines()
    print(lines)
    ##you get the whole html
    

    打印汤:

    f1 = open("E:/soup.txt", "r")
    f2=BeautifulSoup(f1)
    type(f2)
    ##<class 'bs4.BeautifulSoup'>
    print(f2)
    ##prints the whole soup!
    

    如果您收到错误消息:“UnicodeEncodeError: 'charmap' codec can't encode character..” 那是因为您的 cmd 没有使用 'utf8'。所以在 cmd 提示符下输入:chcp 65001 并重试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 2015-06-24
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多