Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在具有BeautifulSoup的网页中找到具有特定类的元素?_Python_Beautifulsoup - Fatal编程技术网

Python 如何在具有BeautifulSoup的网页中找到具有特定类的元素?

Python 如何在具有BeautifulSoup的网页中找到具有特定类的元素?,python,beautifulsoup,Python,Beautifulsoup,我曾尝试在网页中使用此代码查找包含类“data”的表 import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen('http://www.cbssports.com/nba/draft/mock-draft').read()) rows = soup.findAll("table.data") print rows 然而,即使我确信该页上存在一个类为“data”的表,

我曾尝试在网页中使用此代码查找包含类“data”的表

import urllib2
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.cbssports.com/nba/draft/mock-draft').read())

rows = soup.findAll("table.data")
print rows

然而,即使我确信该页上存在一个类为“data”的表,我也没有得到任何行。在使用BeautifulSoup的网页上查找类为“data”的元素的正确方法是什么

rows = soup.find_all('table', attrs = {"class": "data"})

而不是您当前的线路(已测试)。元素的类是一个属性,因此可以在
find\u all
中按属性进行过滤。这一行从示例页面返回一个大的表元素。

如果要提取行,需要以下内容

import urllib2
from BeautifuSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.cbssports.com/nba/draft/mock-draft').read())

# if there's only one table with class = data
table = soup.find('table', attrs = {'class' : 'data'})

# if there are multiple tables with class = data
table = soup.findAll('table', attrs = {'class' : 'data'})[n]
# suppose you need the n-th table of the list returned

rows = table.findAll('tr') # gives all the rows, you can set attrs to filter
然后,您还可以遍历列:

for row in rows:
    cols = row.findAll('td')
    ...

那么,你是在试图分析他们对模拟草稿的选择吗?或者完全做些别的事情?我不知道该说什么——这些代码在我的电脑上工作。唯一的区别是我使用的是“from bs4 import beautifulsou”,而不是问题中的导入行。除此之外,当我运行脚本时,
rows
变量有table元素。这是它弹出的错误TypeError:“NoneType”对象不可调用哪一行?也许你的urlopen呼叫失败了?