【问题标题】:Using bs4 to extract text in html files使用bs4提取html文件中的文本
【发布时间】:2013-08-05 05:52:59
【问题描述】:

想要从我的 html 文件中提取文本。如果我将以下用于特定文件:

import bs4, sys
from urllib import urlopen
#filin = open(sys.argv[1], 'r')
filin = '/home/iykeln/Desktop/R_work/file1.html' 
webpage = urlopen(filin).read().decode('utf-8')
soup = bs4.BeautifulSoup(webpage)
for node in soup.findAll('html'):
    print u''.join(node.findAll(text=True)).encode('utf-8')

它会起作用的。 但是在下面尝试使用 open(sys.argv[1], 'r') 的非特定文件:

import bs4, sys
from urllib import urlopen
filin = open(sys.argv[1], 'r')
#filin = '/home/iykeln/Desktop/R_work/file1.html' 
webpage = urlopen(filin).read().decode('utf-8')
soup = bs4.BeautifulSoup(webpage)
for node in soup.findAll('html'):
    print u''.join(node.findAll(text=True)).encode('utf-8')

import bs4, sys
from urllib import urlopen
with open(sys.argv[1], 'r') as filin:
    webpage = urlopen(filin).read().decode('utf-8')
    soup = bs4.BeautifulSoup(webpage)
    for node in soup.findAll('html'):
        print u''.join(node.findAll(text=True)).encode('utf-8')

我将收到以下错误:

Traceback (most recent call last):
  File "/home/iykeln/Desktop/py/clean.py", line 5, in <module>
    webpage = urlopen(filin).read().decode('utf-8')
  File "/usr/lib/python2.7/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/usr/lib/python2.7/urllib.py", line 180, in open
    fullurl = unwrap(toBytes(fullurl))
  File "/usr/lib/python2.7/urllib.py", line 1057, in unwrap
    url = url.strip()
AttributeError: 'file' object has no attribute 'strip'

【问题讨论】:

    标签: python python-2.7 beautifulsoup html-parsing


    【解决方案1】:

    您不应该调用open,只需将文件名传递给urlopen

    import bs4, sys
    from urllib import urlopen
    
    webpage = urlopen(sys.argv[1]).read().decode('utf-8')
    soup = bs4.BeautifulSoup(webpage)
    for node in soup.findAll('html'):
        print u''.join(node.findAll(text=True)).encode('utf-8')
    

    仅供参考,您不需要urllib 来打开本地文件:

    import bs4, sys
    
    with open(sys.argv[1], 'r') as f:
        webpage = f.read().decode('utf-8')
    
    soup = bs4.BeautifulSoup(webpage)
    for node in soup.findAll('html'):
        print u''.join(node.findAll(text=True)).encode('utf-8')
    

    希望对您有所帮助。

    【讨论】:

    • 是的!它有帮助。@alecxe。谢谢。
    猜你喜欢
    • 2020-02-17
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多