无法从 python 的 html 页面中提取文本

Unable extract text from html page in python

我对网页抓取还很陌生。我阅读了 BeautifulSoup 并尝试使用它。但我无法提取给定 class 名称“company-desc-and-sort-container”的文本。我什至无法从 html 页面中提取标题。这是我试过的代码:

from BeautifulSoup import BeautifulSoup
import requests

url= 'http://fortune.com/best-companies/'    
r = requests.get(url)

soup = BeautifulSoup(r.text)

#print soup.prettify()[0:1000]
print soup.find_all("title")

letters = soup.find_all("div", class_="company-desc-and-sort-container")

我收到以下错误:

 print soup.find_all("title")
TypeError: 'NoneType' object is not callable

您使用的是BeautifulSoup版本3,不仅维护了,而且没有find_all()方法。而且,由于点符号用作 find() 的快捷方式,BeautifulSoup 尝试查找具有 "find_all" 标签名称的元素,结果为 None。然后,它将执行 None("title") 结果为:

TypeError: 'NoneType' object is not callable

升级到BeautifulSoup版本4,替换:

from BeautifulSoup import BeautifulSoup

与:

from bs4 import BeautifulSoup

确保安装了 beautifulsoup4 软件包:

pip install --upgrade beautifulsoup4
soup.find_all("title")

未找到标题标签并 returning "none"。如果 "find_all" 方法确实找到了某些东西,它也会 return 一个列表,你会得到一个不同的错误。您无法打印列表。仅使用 "find" 方法。这将完成第一个标题标签。

那么 html 页面甚至有标题标签吗?搜索,只有在没有 none 时才打印。