从文本文件中读取源页面并提取文本

3
我有多个文本文件,用于存储网站的源页面。因此,每个文本文件都是一个源页面。
我需要使用以下代码从存储在文本文件中的 div 类中提取文本:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("zing.internet.accelerator.plus.txt"))
txt = soup.find('div' , attrs = { 'class' : 'id-app-orig-desc' }).text
print txt

我已经检查了我的soup对象的类型,以确保在查找div类时不使用字符串查找方法。 soup对象的类型是什么?
print type(soup)
<class 'bs4.BeautifulSoup'>

我已经参考了以前的帖子,并在beautifulsoup语句内编写了一个开放性陈述。
错误:
Traceback (most recent call last):
  File "html_desc_cleaning.py", line 13, in <module>
    txt2 = soup.find('div' , attrs = { 'class' : 'id-app-orig-desc' }).text
AttributeError: 'NoneType' object has no attribute 'text'

来自页面的源代码:

enter image description here


不要上传图片,添加文本即可,因为图片没有用处。 - styvane
2个回答

8

尝试替换这个:

soup = BeautifulSoup(open("zing.internet.accelerator.plus.txt"))

使用以下代码:

soup = BeautifulSoup(open("zing.internet.accelerator.plus.txt").read())

顺便说一下,在读取文件后关闭文件是个好主意。你可以像这样使用with

with open("zing.internet.accelerator.plus.txt") as f:
    soup = BeautifulSoup(f.read())

with会自动关闭文件。


这里有一个例子,说明为什么你需要使用.read()函数:

>>> a = open('test.txt')
>>> type(a)
<class '_io.TextIOWrapper'>

>>> print(a)
<_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'>

>>> b = a.read()
>>> type(b)
<class 'str'>

>>> print(b)
Hey there.

>>> print(open('test.txt'))
<_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'>

>>> print(open('test.txt').read())
Hey there.

嘿,谢谢。我尝试了以上代码并包括读取,但仍然遇到相同的错误 :( - Pappu Jha
嗯...尝试使用 print open("zing.internet.accelerator.plus.txt").read() - Remi Guan
它正在打印整个源页面。 - Pappu Jha
不错的开始。尝试使用txt = soup.find_all('div'),而不是txt = soup.find('div', attrs={'class': 'id-app-orig-desc'}).text - Remi Guan
它已经打印了许多 div 类,但不是我要找的那一个。 - Pappu Jha
那就是,open() 函数现在可以使用了。尝试 txt = soup.find('div', {'class': 'id-app-orig-desc'}).text - Remi Guan

2

我已经解决了这个问题。

在我的情况下,beautifulsoup的默认解析器是“lxml”,但无法读取完整的源代码页面。

将解析器更改为“html.parser”对我有用。

f = open("zing.internet.accelerator.plus.txt")
soup = f.read()
bs = BeautifulSoup(soup,"html.parser")
print bs.find('div',{'class' : 'id-app-orig-desc'}).text

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接